Monday, September 24, 2012

Nil and NSNull and NSDictionary

Nil and Null cannot be added into NS collection such as NSDictionary as a value. That is why when checking whether a key exists or not in a dictionary, the following code will work

if ([mydict objectForKey:@"mykey"]) {
    // key exists.
}

However, what about if we really want to add the value for a key that is nil? In this case NSNull is what we want. NSNull can be added in the NSDictionary and also retrieved to represent a nil value.