bijan
bijan

Reputation: 1685

KVO: How to tell observer, that self changed?

In a subclass, whose instance is observed by another object: How to tell the observer that this instance has changed?

What i am trying to do is: I want a NSArrayController to get a notification when a property of some NSManagedObject (the controller manages) has changed. The controller should think the NSManagedObject has changed, but in fact one of its properties did.

Upvotes: 1

Views: 204

Answers (1)

Peter Hosey
Peter Hosey

Reputation: 96333

When setting the property of the managed object, use one of the property's accessor methods (e.g., myObject.foo = bar or [myObject setFoo:bar]) or use KVC ([myObject setValue:bar forKey:@"foo"]). The latter is the only way for a plain NSManagedObject; being able to do the former is one of the advantages of subclassing NSManagedObject.

You can post KVO notifications yourself, but this is only necessary when you're assigning to instance variables (or using setPrimitiveValue:forKey:) directly, which you shouldn't be doing except in a few cases:

  • (Ivars only) In init methods. You shouldn't have any observers yet, so you shouldn't worry about posting KVO notifications.
  • (Ivars only) In dealloc. You shouldn't have any observers anymore, so you shouldn't worry about posting KVO notifications. (If you do still have observers at this point, that is a bug in your code.)
  • (Both ivars and sPV:fK:) In custom accessors. You don't need to post your own KVO notifications from custom accessors because KVO will do this for you. It also lets you set up dependencies, so you don't need to post KVO notifications for other properties, either.

(I've never gotten into Core Data, so I'd appreciate it if any Core Data experts could take a close look over my answer and make sure I haven't gotten anything wrong or left anything out.)

Upvotes: 3

Related Questions