i have a problem with KVO in an iOS App. I can’t seem to get it right. What i’m trying to do:
i have a MenuViewController (revealable on the left side, like facebook app) that observes (and displays) a global value. I tried some different approaches but my App allways crashes (at different points and for different reasons thow). I will describe those below.
Note: I’m using [object addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil] to register the MenuViewController as an observer and [object removeObserver:self forKeyPath:@"name" context:nil] to deregister.
Szenario 1:
o I put the registration as an observer in the -viewWillAppear method and the removeObserver code in -viewWillDisappear.
o When the value changes and the i have completely changes the rootViewController i get an error “message sent to deallocated instance”. So i guess MenuViewController is still registered as an observer.
Szenario 2:
o As a result i putted the removeObserver code into the dealloc function (and later also moved the addObserver part into viewDidLoad)
o Now i get a different error: cannot remove observer for key path “name” from <…> because it is not registered as an observer.
So maybe somebody could give me a hint on my problem and how to do KVO the right way. Unfortunately the docs couldn’t help me so far.
Thanks!
Your view controller does not always get viewWillDisappear before it gets dealloced. Your technique is close to what you should do. You can get multiple viewDidLoad messages (if system unloads your view) and viewWillAppear, but only one dealloc.
What you should do for now is use a BOOL ivar, didObserve. In viewDidLoad, if didObserve == NO, observe the object, set the flag didObserve=YES, then add a log
In dealloc (or anywhere else you want to), add
Now run your app, verify you get the two messages, verify that object is the same object each time (and not nil). This should help you get it sorted out. You might even put a log in ‘observeValueForKeyPath:’ logging any changes to that variable.