On 19 Aug 2008, at 4:23 am, Ryan Brown wrote:

What is the best way to remove a KVO observer if you aren't sure if the object already has an observer registered?


The right answer is to avoid this unsureness (is that a word?).

When I first started using KVO I too thought you could unregister regardless - if it was registered it will unregister, if it wasn't it does nothing. Unfortunately it doesn't work - Cocoa is very fussy about this, and throws exceptions when you try to do things this way with KVO. In addition, each observer has a separate connection so each must be disconnected individually - there is no "disconnect all" available. KVO is not like ordinary notifications.

The point is that observees should not know or care about their observers. Once you stop trying to let observees control their observers your problems will ease considerably. Instead, observers are entirely responsible for their own actions - observing an object and unobserving it later. The main problem usually is the need to unobserve before the observee is deallocated "out from under it". There's no one true way to do this, but just organise your code so that the need doesn't arise. For example a controller that deletes an object can send a "about to delete x" message before it does so that any observers can disconnect from x, or the deletion of an object is handled through a wrapper method that removes the observers. Typically if you look at where and why you are observing an object, a simple approach to managing its observers is usually straightforward. I must admit though that getting it right can be tricky especially if you're trying to fit KVO into an existing model that wasn't built with it in mind.

hth,


Graham
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to