0

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?

1 Answer 1

2

Edit 2

After spending some more time with KVO, I found that in your case, you should be observing person.workplace.address instead of workplace.address. When you observe person.workplace.address, you achieve 2 things:

1) Since you owned the person object, you have absolute control over your object's life cycle. You can now removeObserver at a time of your own choosing.

2) When workplace object is changed, the KVO mechanism will "automagically" observe the new address of the new workplace. Of course, it will notify you of the new address.

Now, you can observe the address without fearing workplace being replaced at random time. This is one of the true hidden power of KVO. This allow subclasses to safely observe any superclass's objects without knowing about their life-cycles.

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.

Original

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];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.