JOM
JOM

Reputation: 8207

How to check NSDictionary for key using Objective-C literals

When parsing JSON, I get NSDictionary and go through it one (known) key at a time. When debugging a bug, I started wondering: how should I handle missing key vs value which is zero?

Earlier I would have used something like this to check if key exists or not:

    if ([dict objectForKey:@"public"])
        newItem.isPublic = [dict objectForKey:@"public"] ? YES : NO;

but now I wrote this using Objective-C object literals. Just started wondering, what does this check actually do:

    if (dict[@"public"])
        newItem.isPublic = dict[@"public"] ? @YES : @NO;

Should I check against nil or [NSNull null] or is there some easier, obvious, way?

Upvotes: 2

Views: 3482

Answers (1)

zoul
zoul

Reputation: 104125

The new literal syntax makes no difference here. The dict[@"public"] code is translated into [dict objectForKeyedSubscript:@"public"], which is documented to be the same as valueForKey:, which in turn calls objectForKey:.

As for the conditional test, writing if ([dict objectForKey:@"foo"]) is the same as if ([dict objectForKey:@"foo"] != nil). In other words, [NSNull null] counts as true here, so you have to check explicitly if you want a different behaviour. Zero can’t be directly stored in a dictionary, it would have to be wrapped in an NSNumber, again being treated as a true value.

See also the Objective-C Literals spec and NSDictionary Class Reference.

Upvotes: 8

Related Questions