Re:Simple iOS Key Value Observing (KVO) Explained
by pothibo on Wednesday January 04, 2012 @10:57AM
(#3424554)
Yeah, I'm sorry. I first entered a comment saying that the website was down due to "Error establishing a database connection" and I saw your comment and decided to comment on it.
I then forgot to say I couldn't read the post since the site was down:( I will read it when it gets back online.
If you look at the Key Value Observing Protocol you will find two methods that allow you to remove an observer again (remember: You have to remove an observer at the appropriate time - otherwise you will receive exceptions and your app will probably crash):
removeObserver:forKeyPath: and removeObserver:forKeyPath:context:. The first one has been around forever but it does not allow you to specify a context - only an observer and a path. This is problematic and andrewsardone gave you an example. This is why Apple introduced the second method in 10.7/iOS 5 which allows you to specify a (unique) context. The documentation says:
"Examining the value in context you are able to determine precisely which addObserver:forKeyPath:options:context: invocation was used to create the observation relationship. When the same observer is registered for the same key-path multiple times, but with different context pointers, an application can determine specifically which object to stop observing."
Always specifying a context makes your app more robust.