Search code examples
iosobjective-ccore-datansmanagedobjectcontext

NSManagedObjectContextObjectsDidChangeNotification for one entity


It's possible with NSManagedObjectContextObjectsDidChangeNotification to get a notification only when a specific entity changes?

I want to update my view when my contact information or avatar changes, but with NSManagedObjectContextObjectsDidChangeNotification I'm getting a notification every time something gets changed on the database.

It's possible to do that with NSManagedObjectContextObjectsDidChangeNotification?


Solution

  • I don't believe it is possible to have it only trigger for a specific entity. However, the notification does provide information on which objects were changed. The notification contains a dictionary (userInfo) which contains 3 keys:

    • NSDeletedObjectsKey - array of all objects that have been deleted
    • NSInsertedObjectsKey - array of all objects that have been added/inserted
    • NSUpdatedObjectsKey - array of all objects that have been modified

    You can iterate over the contents of those arrays and determine if your particular object has been changed. A rough outline is below:

    - (void) handleObjectsChangedNotification:(NSNotification*) notification {
        // Iterate over all of the deleted objects
        for (NSManagedObject* object in notification.userInfo[NSDeletedObjectsKey]) {
        }
    
        // Iterate over all of the new objects
        for (NSManagedObject* object in notification.userInfo[NSInsertedObjectsKey]) {
        }
    
        // Iterate over all of the modified objects
        for (NSManagedObject* object in notification.userInfo[NSUpdatedObjectsKey]) {
        }
    }