MrTJ MrTJ - 20 days ago 8
iOS Question

Safe Key Value Observing of keypaths

I am trying to implement a safe key value observing on keypaths. Let's suppose that I have a data model object named

person
that have a
workplace
property. The
workplace
in turn have a
address
property that I wish to observe so I set up key value observing with the following call:

[person addObserver:theObserver
forKeyPath:@"workplace.address"
options:NSKeyValueObservingOptionNew
context:NULL];


This works fine until the person does not change workplace. As soon as this happens:

person.workplace = newWorkplace;


the KVC system crashes the application correctly saying that "oldAddress was deallocated while key value observers were still registered with it". (being oldAddress the address of the previous workplace).

Unfortunately I can not tweak the implementation of the class of 'person' object to notify the observer that workplace is going to go away. Are there any pattern to avoid this kind of crash? Maybe one can get some other notifications? How is the keypath being traversed in the case of KVC and do you have access to this chain?

Answer

You can observe the keyPath "workplace" on the person object. When this keyPath is invoked, you simply removeObserver for "workplace.address".

[person addObserver:theObserver forKeyPath:@"workplace" options:[NSKeyValueObservingOptionNew] context:NULL];

Edit 1

Best practice to remove an object as observer for some KVO property

The accepted answer in this thread best described your situation. You should not have observe the property "address" in the first place, since you have no control over the life-cycle of "workplace". You have a design issue.