Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access object of Nested NSDictionary

Is there a way to directly access an inner-Dictionary of an outer Dictionary in Objective-C? For example, I have key to an object which is part of inner dictionary, Is there any way to directly access object from that key.

GameDictionary {
  Indoor_Game = { "game1" = chess; "game2" = video_Game; "game3" = poker; };
  OutDoor_Game = { "game4" = cricket; "game5" = hockey; "game6" = football; };
};

I have a key "game4", but I don't know in which dictionary object of this key is present, currently I have to search in each dictionary for object, the code which I am using is:

NSString* gameName = nil;
NSString* gameKey = @"game4";
NSArray* gameKeys = [GameDictionary allKeys];
for (int index = 0; index < [gameKeys count]; index ++) {
  NSDictionary* GameType = [GameDictionary objectForKey:[gameKeys objectAtIndex:index]];
  if ([GameType objectForKey:gameKey]) {
    gameName = [GameType objectForKey:gameKey];
    break;
  }
}

Is their any easy way to access directly to the inner dictionary instead of for loops.

like image 211
Mayur Avatar asked Sep 24 '13 06:09

Mayur


1 Answers

valueForKeyPath looks like what you want.

[GameDictionary valueForKeyPath:@"OutDoor_Game"]
//would return a dictionary of the games - "game4" = cricket; "game5" = hockey; "game6" = football;

[GameDictionary valueForKeyPath:@"OutDoor_Game.game4"]
//would return cricket

https://developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Conceptual/KeyValueCoding/Articles/CollectionOperators.html

like image 200
Oliver Atkinson Avatar answered Oct 07 '22 13:10

Oliver Atkinson