It's pretty easy to observe a one-to-many relationship if everything you want to know is added, deleted, replaced, or reordered. In fact, this is done exactly the same as with a regular object:
[self addObserver:self forKeyPath:@"locations" options:0 context:NULL];
Then do the following to receive notifications (partially copied from Apple docs):
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqual:@"locations"]) {
Do not forget to stop at some point:
[self removeObserver:self forKeyPath:@"locations"];
And, although you did not ask if you want to know if the object has any of the objects in (and not just the NSSet that you are looking here), then you should observe individual objects.
EDIT
In your comment you want to observe individual objects. This is pretty straightforward for “normal” objects, but a managed object requires a bit more work because you have to observe separate keys in the object that would look something like this:
- (void)observeManagedObject:(NSManagedObject *)myObject { NSArray *myObjectKeys = [[[myObject entity] attributesByName] allKeys]; for (NSString *key in myObjectKeys) { [myObject addObserver:self forKeyPath:key options:0 context:nil]; } }
And then you observe all NSManagedObjects in the array as follows:
for (NSManagedObject *object in myArray) { [self observeManagedObject:object]; }
Do the opposite to stop monitoring keys on the managed entity!
source share