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​)​ ​{​ ...

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.