How do you remove KVO from a weak property? How do you remove KVO from a weak property? ios ios

How do you remove KVO from a weak property?


I find any kind of code required specially for this case really unnecessary as removal can be automated.

With the introduction of ARC, Apple should have provide automatic removal of observers that would fix cases like this, but unfortunately they didn't. But I've made my own category that adds this lacking feature: https://github.com/krzysztofzablocki/SFObserversI've explained how I did manage that on my blog: http://www.merowing.info/2012/03/automatic-removal-of-nsnotificationcenter-or-kvo-observers/

If you look at my solution you will notice, that it makes sure that original code is called, even if one of the methods call other ones, so that even if apple changes its internal behavior the category will still work fine :)


You could define an explicit weak property referencing the superview and then observe self with a key path like @"propertyReferringSuperview.propertyOfSuperview"? When you get a KVO notification, you check if self.propertyReferringSuperview == nil and stop observing @"propertyReferringSuperview.propertyOfSuperview".


Instead of adding a weak property, you could just use the superview property and implement willMoveToSuperview: to add/remove the KVO observation.

- (void)willMoveToSuperview:(UIView *)newSuperview {    [self.superview removeObserver:self forKeyPath:@"contentOffset" context:context];    [newSuperview addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:context];    [super willMoveToSuperview:newSuperview]; // optional as default implementation does nothing}