Identifying which fields have changed before CoreData saves
Asked Answered
G

1

14

//set up notifications

[[NSNotificationCenter defaultCenter]
 addObserver:self
 selector:@selector(dataChanged:)
 name:NSManagedObjectContextDidSaveNotification
 object:context];    

//later

- (void)dataChanged:(NSNotification *)notification{
  NSDictionary *info = notification.userInfo;
  NSSet *insertedObjects = [info objectForKey:NSInsertedObjectsKey];
  NSSet *deletedObjects = [info objectForKey:NSDeletedObjectsKey];
  NSSet *updatedObjects = [info objectForKey:NSUpdatedObjectsKey];

Is there anyway to determine from the updatedObjects which fields were actually changed?

thanks, Michael

Gerger answered 12/5, 2011 at 10:11 Comment(0)
D
19

The following should do the trick, but you will need to use NSManagedObjectContextWillSaveNotification and access your updated objects through the same NSManagedObjectContext used to save the objects.

for(NSManagedObject *obj in updatedObjects){

   NSDictionary *changes = [obj changedValues];
   // now process the changes as you need

}

See the discussion in the comments.

Demoniac answered 12/5, 2011 at 11:17 Comment(4)
This is very helpful. Thank you. After some experimentation, I determined that changedValues will always be empty for NSManagedObjectContextDidSaveNotification, since the values have already been saved. Does that seem right to you? I did determine that if I use NSManagedObjectContextWillSaveNotification I can use [notification object] which returns the NSManagedObjectContext. From there I can call [context updatedObjects] and from the updated object i can call [obj changedValues] as you had indicated. Then I can see which values are about to change if the save proceeds.Gerger
Yes: you need to access the original NSManagedObjectContext where the changes were made for this to work.Demoniac
@MassimoCafaro I get empty dictionary from "changedValues" method. I have an Entity "Guest" which has one to one relationship with another Entity "PersonalDetails". If i changed anything in PersonalDetails, I get "Guest" and "PersonalDetails" both in updatedObjects but changedValues returns empty dictionary.Radiograph
@iVishal, as discussed in the comments, you need to use the same NSManagedObjectContext that you used to modify your objects, and NSManagedObjectContextWillSaveNotification. Indeed, if you use NSManagedObjectContextDidSaveNotification and save the objects, you loose the modifications made to your objects once the objects are saved.Demoniac

© 2022 - 2024 — McMap. All rights reserved.