KVO: when to stop observing?
KVO: when to stop observing?
- Subject: KVO: when to stop observing?
- From: Michel Schinz <email@hidden>
- Date: Sun, 30 Aug 2009 08:59:54 +0200
Hi,
In my program, I rely heavily on key-value observing (KVO), which I
find really useful. However, I haven't found a good way to know when I
should stop observing, i.e. call "removeObserver:forKeyPath:".
Until now, my solution has been to start observing in the designated
initialiser, and to stop observing in the "dealloc" method. This
solution kind of works, but has several drawbacks:
1. It doesn't work with GC, first because GC doesn't call "dealloc"
and second because the simple fact that my object is registered as an
observer probably prevents it from being collected in the first place
(I haven't checked, but that's what I gather from messages found in
this list's archive). Even if it didn't, stopping the observation in
"finalize" wouldn't be ideal, as object would keep getting
notifications for some time after becoming unreachable.
2. I have to be careful when I use this technique on CoreAnimation
layers, since CA uses the "initWithLayer:" method to create
presentation layers during animations. If "initWithLayer:" doesn't
invoke the designated initialiser, then the presentation layer doesn't
observe anything, and the program crashes when its "dealloc" method
tries to call "removeObserver:forKeyPath:". The "solution" I have
found for this is to keep track of whether a layer is a presentation
layer or not, and only call "removeObserver:forKeyPath:" for non-
presentation layers. That's ugly.
Overall, I have something that works but isn't elegant at all. I'm
therefore looking for better solutions, and would be interested to
know what people have come up with.
It seems to me that the only clean solution would be to detect when an
object is "dead" and then call a method to make it stop all its
observations, but this is equivalent to solving the memory management
problem by hand, which is painful.
Thanks,
Michel.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
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:
This email sent to email@hidden