Key data: monitoring a new object of a certain type

I would like to receive notifications when an object of a certain type is added (and possibly changing / deleting it).

I read that this is possible by adding an observer to managedObjectContext. However, I did not find a real way to do this.

I do:

[context addObserver:self forKeyPath:@"{myEntityName}" options:{I have tried several different values, but I am failing to understand which one to use} context:@"NewEntity"]; 

Thanks for the help.

Note. I am obviously new to coredata / cocoa / objective-c, and it is probably very simple, but it has been chasing the answer for too long. It is impossible to find examples and / or explanations of how to correctly observe changes for a context object (I could observe changes on specific objects without problems).

By the way: this is a similar question, which suggests that it is possible, but I don’t have enough details: Basic data: Monitoring all changes in Entity of a certain type

+4
source share
2 answers

First, do not confuse objects and objects. Objects are abstractions related to classes, and they are never added or removed from the context of a managed object. These are managed objects that are added or removed from the context of a managed object. Each managed object is bound to an entity in a data model, just like any other instance of an object is bound to a specific class.

So, you really need to know when a managed object attached to a specific object is inserted / updated / deleted.

The easiest way to handle this is to register for context:

 NSManagedObjectContextObjectsDidChangeNotification 

... which will provide a notification whenever a managed entity in the context is inserted / updated / deleted. To find only managed objects that are bound to a specific object, check the objects returned by the NSInsertedObjectsKey, NSUpdatedObjectsKey, and NSDeletedObjectsKey keys, and then check the entity property for each object.

Alternatively, you use your own subclass of NSManagedObject and override awakeFromInsert to give a notification when an object is first inserted.

I would notice that such functionality is rarely needed. When you find that you are connecting a large number of notifications, this usually indicates that your data model needs to be processed to get more information. You usually need notifications because some key logic of the data model is not encoded in Core Data, but is in an external object that needs to be notified.

+8
source

Instead, I choose this approach, it feels cleaner:

  • Create an entity-based NSArrayController (use an interface constructor to write less code)
  • Observe the arrangedObjects path to your array controller
  • Done.
0
source

All Articles