0

With literals syntax one can use NSDictionary *dictionary like this to get the objectForKey

NSDictionary * dictionary;
id object = dictionary[key];

But if the type of dictionary is of type id and you try to write

id dictionary;
id object = dictionary[key];

This will work until if your dictionary was really a dictionary otherwise it would crash.

The solution for that would be to have a method

-(id)safeObject:(id)object forKey:(id)aKey {
    if (![object isKindOfClass:[NSDictionary class]]) {
        return nil;
    }
    return [object objectForKeyedSubscript:aKey];
}

So now when I call it like this

id dictionary;
id object = [self safeObject:dictionary forKey:key];

This won't crash. But the problem with this one is that If I have to go deeper in the nested dictionary for example

id object = dictionary[key1][subKey1][subsubKey1];

It is really convenient to write with the literal syntax with old syntax it would be something like

id mainObject = [self safeObject:dictionary forKey:key1];
id subObject = [self safeObject:mainObject forKey:subKey1];
id object = [self safeObject:subObject forKey:subsubKey1];  

So not that much readable. I want to have this solution with new literal syntax is this possible?

hariszaman
  • 8,202
  • 2
  • 40
  • 59

1 Answers1

0

You could use valueForKeyPath, e.g.

id dictionary = @{@"key":@{@"subkey" : @{ @"subsubkey" : @"value"}}};
id object = [self safeObject:dictionary];
id value = [object valueForKeyPath:@"key.subkey.subsubkey"];

Also slightly change safeObject only to check if it's a dictionary,

- (id)safeObject:(id)object {
    if (![object isKindOfClass:[NSDictionary class]]) {
        return nil;
    }
    return object;
}

Hope this helps, is this what you're looking for?

JingJingTao
  • 1,760
  • 17
  • 28