【问题标题】:Access object of Nested NSDictionary嵌套 NSDictionary 的访问对象
【发布时间】:2013-09-24 06:40:11
【问题描述】:

有没有办法在 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 循环。

【问题讨论】:

    标签: objective-c nsdictionary nsmutabledictionary


    【解决方案1】:

    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

    【讨论】:

    • 对于收集操作,您需要完整的路径,例如:-“OutDoor_Game.game4”,但我只有一半路径是“game4”。
    • @Mayur 这是你控制的数据结构吗?您可能需要考虑重新处理它以更好地重用。类似:pastebin.com/xUCmGq4c
    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    相关资源
    最近更新 更多