objective-c

How to allow NSMutableDictionary to accept 'nil' values?


I have this statement:

[custData setObject: [rs stringForColumnIndex:2]  forKey: @"email"];

where [rs stringForColumnIndex:2] obtained from a SQLite3 d/b has a value of nil. The app crashes giving me the error:

NSCFDictionary setObject:forKey:]: attempt to insert nil value (key: email)'

Is there a way to prevent this? (like a setting for NSMutableDictionary?)

UPDATE: this is what I finally did:

[custData setObject: ([rs stringForColumnIndex:2] != nil? [rs stringForColumnIndex:2]:@"") forKey: @"email"];

Solution

  • There is a non-nil object called NSNull that is built specifically to represent nils in situations where "plain" nil is not acceptable. If you replace your nils with [NSNull null] object, NSDictionary will take them. You would need to check for NSNull on the way out, though.

    Note that this is important only when you must differentiate between a value not being set and a value being set to nil. If your code is such that it can interpret a missing value as nil, you do not need to use NSNull at all.