Say I have a list of model objects and a controller object which is interested in property changes to the individual model object. When I add the object, I use addObserver for each key it is interested in using KVO between the controller and the model object. Now, when one of the observed objects goes away, I need to tell the view controller to stop observing the changes on this individual object for the particular key.
What is an elegant way of doing this? The best way I can think of is to add a new key kRemoveObject which I call addObserver on in my controller that gets triggered right before the object gets deleted. Then I remove all the observed keys, including kRemoveObject for the particular instance. Does anyone know of a cleaner way? This seems a little bit cumbersome.
I found this very elegant way of doing it and it solves one of the things that has always bothered me about KVO which is the large “switch statement” that KVO adds with observeValueForKeyPath. KVO+Blocks is very cool, it eliminates that “switch statement” and it automatically handles removal of the observer so no need to call removeObserver when using ARC (if you are doing your own memory management then I think you need to call removeObserverWithBlockToken, although I have not tried it).
http://blog.andymatuschak.org/post/156229939/kvo-blocks-block-callbacks-for-cocoa-observers
Code here:
https://gist.github.com/153676
One thing to be careful of, but is true of blocks in general, is if you reference self in your block. You need to do this:
if you don’t you will end up with a retain cycle. (see Retain cycle on `self` with blocks for more details).
One other thing, it works with ARC if you put -fno-objc-arc on the file. (See this for details How can I disable ARC for a single file in a project?)
I hope that Apple adds something like this to the SDK.