Perfect KVO here includes two parts: add observer correctly and remove observer correctly.
The story:
- I use one UITableViewCell(cell) to display one NSManagedObject(object).
- Each object has some dynamic properties that need observing by its cell.
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:
- Where is the best place to put the observer removing code?
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.