Perfect KVO here includes two parts: add observer correctly and remove observer correctly.
The story:
Not all objects have the same set of observed properties. I add key path observers selectively like this:
if (object.thumbnail_pic_url) [object addObserver:cell forKeyPath:@"thumbnail_picture" options:0 context:NULL];
Object could be deleted. I must remove observers when object is deleted. The database is very large and complex so I definitely don't want to register all cells to receive moc notifications like NSManagedObjectContextObjectsDidChangeNotification. But I can accept to add a cell ivar in object if I have to, even though it goes agains good Modle-View-Controller design pattern.
The problem: How can I correctly remove the observer(cell) for all the registered key paths from an object when it is deleted?
In fact, it is a big problem that can be divided into two small problems:
How do I determine which key paths to unregister? I can't query its properties after an object is deleted — it will cause unfulfillable faults, so I can't write code like this:
if (object.thumbnail_pic_url) [object removeObserver:cell forKeyPath:@"thumbnail_picture"];
and I can't either blindly remove observer for unregistered key path — exceptions(Cannot remove an observer for the key path "thumbnail_picture" from because it is not registered as an observer.) will be thrown up.
an0,
There is an NSManagedObject method just for doing deletion timed functions: -prepareForDeletion.
Its documentation claims: "You can implement this method to perform any operations required before the object is deleted, such as custom propagation before relationships are torn down, or reconfiguration of objects using key-value observing."
You could also look at using: -willTurnIntoFault and -didTurnIntoFault. But I think you'll be happier using -prepareForDeletion.
Andrew
P.S. This method is documented in the class reference. I respectfully suggest that you save time by reading the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With