O'Reilly logo

Cocoa Programming for OS X: The Big Nerd Ranch Guide by Aaron Hillegass, Adam Preble, Nate Chandler

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

KVC and nil

What do you think happens if you use KVC to set a numeric type, such as a Float or Int, to nil?

s​e​t​V​a​l​u​e​(​n​i​l​,​ ​f​o​r​K​e​y​:​ ​"​t​e​m​p​e​r​a​t​u​r​e​"​)​

Instead of making an assumption, such as assigning the value 0, KVC’s designers decided to let the object decide what to do. When nil is set for numeric type, KVC calls the method setNilValueForKey(_:). The default implementation on NSObject throws an exception.

Although it is not needed in this application – none of the controls will try to set it to nil – you could implement setNilValueForKey(_:) on MainWindowController to handle this situation:

 ​ ​ ​ ​o​v​e​r​r​i​d​e​ ​f​u​n​c​ ​s​e​t​N​i​l​V​a​l​u​e​F​o​r​K​e​y​(​k​e​y​:​ ​S​t​r​i​n​g​)​ ​{​ ...

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