iOS KVO 观察另一个class 属性

iOS KVO observe another class property

有没有观察另一个 class 属性,比如观察 iOS 中的单例实例。我试过了,但我不知道从另一个class.

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

你试过这样做吗:

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

addObserver消息的接收者是被观察对象。所以它应该是你的单例实例。 keypath 应该以这个单例的可观察 属性 的名称开头。例如:

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

一个键路径可以包含一个由点分隔的 属性 名称链。只是为了说明:如果你想观察键 window 的根视图控制器,你可以这样做

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