KVO – How to check if an object is an observer?

[…] is it possible to check if an object actually is observing that property? No. When dealing with KVO you should always have the following model in mind: When establishing an observation you are responsible for removing that exact observation. An observation is identified by its context—therefore, the context has to be unique. When receiving … Read more

Swift 4 approach for observeValue(forKeyPath:…)

Swift 4 introduced a family of concrete Key-Path types, a new Key-Path Expression to produce them and a new closure-based observe function available to classes that inherit NSObject. Using this new set of features, your particular example can now be expressed much more succinctly: self.observation = object.observe(\.keyPath) { [unowned self] object, change in self.someFunction() } … Read more

Observing an NSMutableArray for insertion/removal

But shouldn’t the synthesized accessors automatically return such a proxy object? No. What’s the proper way to work around this–should I write a custom accessor that just invokes [super mutableArrayValueForKey…]? No. Implement the array accessors. When you call these, KVO will post the appropriate notifications automatically. So all you have to do is: [myObject insertObject:newObject … Read more

How can I do Key Value Observing and get a KVO callback on a UIView’s frame?

There are usually notifications or other observable events where KVO isn’t supported. Even though the docs says ‘no’, it is ostensibly safe to observe the CALayer backing the UIView. Observing the CALayer works in practice because of its extensive use of KVO and proper accessors (instead of ivar manipulation). It’s not guaranteed to work going … Read more