2

One of my methods needs to return nil if no value exists in an dictionary for a specific key or if the value is not of class NSArray.

This could be done like this:

if (![dict objectForKey:@"key"]) return nil;

id tmp = [dict objectForKey:@"key"];
return  [tmp isKindOfClass:[NSArray class]] ? tmp : nil;

I was wondering whether it is well defined to write this mess as:

if (![[dict objectForKey:@"key"] isKindOfClass:[NSArray class]]) return nil;
return [dict objectForKey:@"key"];

What happens here if [dict objectForKey:@"key"] returns nil?

jscs
  • 63,694
  • 13
  • 151
  • 195
user7802048
  • 183
  • 6
  • 2
    It wouldn't be hard to test, but in objective-C you can safely send messages to `nil` - it will just return `nil` which is false. Personally, I prefer your first form, but without the unnecessary initial `if` It only accesses the dictionary once and has a single return – Paulw11 Jun 16 '17 at 23:45
  • @Paulw11 Thank you really much! I'll go with your recommended form. – user7802048 Jun 17 '17 at 12:10

0 Answers0