Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSManagedObject's hasChanges is true while changedValues is empty

I am trying to observe individual NSManagedObject changes on NSManagedObjectContextWillSaveNotification:

- (void)managedObjectContextWillSave:(NSNotification *)notification
{
    for (NSManagedObject * object in self.mutableObservedManagedObjects)
    {
        if (object.hasChanges)
        {
            [self managedObjectWasUpdated:object];
        }
    }
}

The problem is that hasChanges is true while object.changedValues is empty, thus wrongly (?) triggering managedObjectWasUpdated:.

I'm trying to understand why this is the case and if I should better check object.changedValues.count before calling managedObjectWasUpdated:.


isInserted and isDeleted are both false.

like image 544
Rivera Avatar asked Oct 10 '14 07:10

Rivera


1 Answers

In my experience, if the entity already existed, you loaded it and then you set a value to a property that is equal to its previous value, then the record will be marked as updated, hasChanges will return YES, and changedValues will be empty. When you save the context, what gets updated is a special Core Data column called Z_OPT, which refers to the number of times an entity has been updated. For these situations you can do something like this before saving:

for (NSManagedObject *managedObject in context.updatedObjects.objectEnumerator) {
    if (!managedObject.changedValues.count) {
        [context refreshObject:managedObject mergeChanges:NO];
    }
}

in order to don't even update the Z_OPT value.

like image 87
Gian Franco Zabarino Avatar answered Oct 05 '22 19:10

Gian Franco Zabarino