Access object of Nested NSDictionary
Asked Answered
E

1

5

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.

Eventual answered 24/9, 2013 at 6:40 Comment(0)
G
7

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

Geibel answered 24/9, 2013 at 6:56 Comment(2)
For collection Operations you need complete path like:- "OutDoor_Game.game4", but I have only half path which is "game4".Eventual
@Eventual Is this a data structure you control? you might want to consider re-working it for better reuse. something like: pastebin.com/xUCmGq4cGeibel

© 2022 - 2024 — McMap. All rights reserved.