Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data: Observing new Entity of certain type

I would like to be notified whenever an entity of a certain type is added (and maybe changed/removed).

I read it is possible by adding an observer to the managedObjectContext. However, I haven't found an actual way to do it.

I am doing:

[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 this is probably very basic, but has been chasing for an answer for too long. Can't find samples and/or explanations on how to properly observe the changes for the context object (I have been able to observe changes on specific entities without issues).

BTW: this is a similar question that suggests this is possible, but I am lacking the details: Core Data: Observing all changes on Entity of certain type

like image 924
rufo Avatar asked Sep 01 '11 21:09

rufo


1 Answers

Firstly, don't confuse entities and objects. Entities are abstractions akin to classes and they are never added to or removed from a managed object context. It is the managed objects that are added to or removed from a managed object context. Each managed object is keyed to entity in the data model just like any other object instance is keyed to a particular class.

So,what you really want is to be notified when a managed object keyed to a particular entity is inserted/updated/deleted.

The easiest way to handle this is to register for the context's:

NSManagedObjectContextObjectsDidChangeNotification

… which will provide a notification whenever a managed object in the context is inserted/updated/deleted. To find only the managed objects keyed to a particular entity check the objects returned by the NSInsertedObjectsKey, NSUpdatedObjectsKey, and NSDeletedObjectsKey keys and then check the entity property of each object.

Alternatively, you use a custom NSManagedObject subclass and override awakeFromInsert to issue a notification when the object is first inserted.

I would note that such a functionality is rarely needed. When you find yourself wiring up a lot of notifications, that is usually an indication that your data model needs reworking to capture more information. You usually need notifications because some key logic of the data model is not encoded in Core Data but resides in an external object that needs the notification.

like image 99
TechZen Avatar answered Sep 16 '22 14:09

TechZen