Search code examples
ioscore-datansmanagedobjectnsmanagedobjectcontext

Track attribute change of NSManagedObject


I'm looking for a way to track the attribute change of an NSManagedObject.

Currently I use a NSNotifactionCenter to see the changes of my managedobjectcontext:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDataModelChange:) name:NSManagedObjectContextObjectsDidChangeNotification object:self.managedObjectContext];

It fires the handleDataModelChange Methode which looks like this:

- (void)handleDataModelChange:(NSNotification *)note
{
    NSSet *updatedObjects = [[note userInfo] objectForKey:NSUpdatedObjectsKey];

    if (updatedObjects.count > 0) {
        for (NSManagedObject *obj in updatedObjects.allObjects) {
            NSLog(@"Object updated: %@ with values:",obj.entity.name);
            NSDictionary *theAttributes = [self getAllAttributesOf:obj];
            for (NSString *attributeName in theAttributes) {
                NSLog(@"Name: %@ : %@",attributeName,[obj valueForKey:attributeName]);
            }
        }
    }
}

This logs the new attributes of the object if it changed. How can I achieve a way to get the old attribute values as well?


Solution

  • From the NSManagedObject Class Reference:

    changedValues

    Returns a dictionary containing the keys and (new) values of persistent properties that have been changed since last fetching or saving the receiver.

    changedValuesForCurrentEvent

    Returns a dictionary containing the keys and old values of persistent properties that have changed since the last posting of NSManagedObjectContextObjectsDidChangeNotification.