Search code examples
iosobservers

iOS KVO observe another class property


Is there anyway observe another class propery, like observe an singleton instance in iOS. I have tried, but I don't know hot to write keypath from another class.

[self addObserver:self forKeyPath:@"otherclass/keypath" options:NSKeyValueObservingOptionNew context:NULL];

Solution

  • The receiver of the addObserver message is the observed object. So it should be the instance of your singleton. The keypath should start with the name of a observable property of this singleton. E.g.:

    [[SingletonClass instance] addObserver:self forKeyPath:@"propertyName" options:NSKeyValueObservingOptionNew context:NULL];
    

    A keypath can contain a chain of property names which are separated by dots. Just for illustration: If you want observe the root view controller of the key window, you can do

    [[UIApplication sharedApplication] addObserver:self 
        forKeyPath:@"keyWindow.rootViewController" 
        options:NSKeyValueObservingOptionNew context:NULL];