Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 16: Key-Value Coding > The Nils Are Alive

The Nils Are Alive

This discussion of nil values brings up an interesting question. What does "nil" mean for a scalar value, like for mileage. Is it zero? Is it −1? Is it pi? There's no way for Cocoa to know. You can try like this:

[car setValue: nil forKey: @"mileage"];

But Cocoa gives you the smack-down:


'[<Car 0x105740> setNilValueForKey]: could not set nil as the value for the
key mileage.'

To fix this problem, you override -setNilValueForKey and provide whatever logic makes sense. We'll make an executive decision and say that nil mileage means to zero out the car's mileage, rather than using some other value like −1:

- (void) setNilValueForKey: (NSString *) key {
    if ([key isEqualToString: @"mileage"]) {
        mileage = 0;
    } else {
        [super setNilValueForKey: key];
    }
} // setNilValueForKey

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint