For the More Curious: Dependent Keys

In some cases a value may be dependent on another. For example, if you have a Person class with a computed property fullName that is dependent on the properties firstName and lastName, wouldn’t it be nice if observers of fullName could be notified when either firstName or lastName changes? KVO’s designers thought so, too, which is why they implemented a convention for defining dependent keys.

To define a key’s dependencies you must implement a specially named class method which returns a Set of key paths. In the example above you would implement keyPathsForValuesAffectingFullName():

c​l​a​s​s​ ​P​e​r​s​o​n​ ​{​ ​ ​ ​ ​d​y​n​a​m​i​c​ ​v​a​r​ ​f​i​r​s​t​N​a​m​e​ ​=​ ​"​"​ ​ ​ ​ ​d​y​n​a​m​i​c​ ...

Get Cocoa Programming for OS X: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.