Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does observeValueForKeyPath get called?

Does it get called after a property is changed (meaning property setter is already popped from call stack) or when a property setter is executing?

Swift has very handy "Property observers". Does Obj-C have something similar for KVO?

like image 267
David Liu Avatar asked Nov 09 '22 09:11

David Liu


1 Answers

That depends on what options were used when the observer was added. If the observer was added with NSKeyValueObservingOptionPrior, then -observeValueForKeyPath:... is called both before and after the property is changed. Or, more accurately, it's called both during the -willChange... and during the -didChange... methods.

If NSKeyValueObservingOptionPrior was not used, then -observeValueForKeyPath:... is only called after the property is changed. (During the -didChange... method.)

Swift property observers aren't really similar to KVO. Rather, they are more like implementing the property setter yourself (or overriding it in a subclass) and doing something before and/or after actually changing the instance variable that backs the property (or calling through to super).

I recommend against writing a class that uses KVO on its own properties to respond to changes. Instead, it should implement the setter to do something when a property changes.

like image 151
Ken Thomases Avatar answered Dec 15 '22 06:12

Ken Thomases