views:

1182

answers:

3

I need to check if an dict has a key or not. How?

+5  A: 

objectForKey will return nil if a key doesn't exists.

Adirael
And what if the key does exist, but it's corresponding value is nil?
Fyodor Soikin
That's not possible. You can't add nil to a NSDictionary. You would have to use `[NSNull null]` instead.
Ole Begemann
@fyodor an nsdictionay will throw an NSInvalidArgumentException if you attempt to insert a nil value, so there should never be a case where a key exists, but the corresponding value is nil.
Brad Smith
+2  A: 
if ([mydict objectForKey:@"mykey"]) {
    // key exists.
}
else
{
    // ...
}
ChristopheD
+2  A: 
if ([[dictionary allKeys] containsObject:key) {
    // contains key
}

or

if ([dictionary objectForKey:key]) {
    // contains key
}
Aleksejs