MrTJ MrTJ - 1 year ago 83
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

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

[person addObserver:theObserver

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download