O'Reilly logo

Objective-C Programming: The Big Nerd Ranch Guide by Mikey Ward, Aaron Hillegass

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

35 Key-Value coding

Key-value coding is the ability to read and set a property using its name. The key-value coding methods are defined in NSObject, and thus every object has this capability.

Open main.m and find the line:

 ​ ​ ​ ​[​a​ ​s​e​t​P​r​o​d​u​c​t​N​a​m​e​:​@​"​W​a​s​h​i​n​g​ ​M​a​c​h​i​n​e​"​]​;​

Rewrite the same line to use key-value coding:

 ​ ​ ​ ​[​a​ ​s​e​t​V​a​l​u​e​:​@​"​W​a​s​h​i​n​g​ ​M​a​c​h​i​n​e​"​ ​f​o​r​K​e​y​:​@​"​p​r​o​d​u​c​t​N​a​m​e​"​]​;​

In this case, the setValue:forKey: method, as defined in NSObject, will go looking for a setter method named setProductName:. If the object does not have a setProductName: method, it will access the instance variable directly.

You can also read the value of ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required