Search code examples
iphoneioscore-datakey-value-observing

CoreData register global observer for all objects and keys


how can / should I register a KVO observer for all entities and keys, regardless of their type?

The purpose of this is to monitor changes to objects and mark them as modified, so that I can provide sync functionality through a JSON API with a web service.

Also, if I'm doing this wrong, what's the right way?

EDIT: Not that this is going to be used in production code and I'd rather not risk using a library that is immature.


Solution

  • NSManagedObjectContextObjectsDidChangeNotification is your friend.

    This notification posts once per run loop iteration, and contains dictionaries of everything that's been changed/inserted/deleted/merged.

    Two things to beware of:

    If you're doing fancy thread/operation queue tricks, you may have to call processPendingChanges manually in some cases if this notification doesn't seem to be posting when you expect it. Normally CD schedules it on the current run loop automatically when needed.

    When you register for this notification, be specific about which managed object context you want to hear from (don't just pass nil.) Internal frameworks use Core Data privately, and this notification may get posted by contexts you don't expect.