嵌套NSDictionary的访问对象

时间:2013-09-24 06:40:11

标签: objective-c nsdictionary nsmutabledictionary

有没有办法在Objective-C中直接访问外部词典的内部词典?例如,我有一个对象的键,它是内部字典的一部分,有没有办法从该键直接访问对象。

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

我有一个键“game4”,但我不知道这个键的哪个字典对象存在,目前我必须在每个字典中搜索对象,我使用的代码是:

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;
  }
}

他们可以直接访问内部词典而不是for循环。

1 个答案:

答案 0 :(得分:7)

valueForKeyPath看起来就像你想要的那样。

[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