【问题标题】:How to read all NSDictionary objects for a key to an array如何读取所有 NSDictionary 对象以获取数组的键
【发布时间】:2010-11-27 13:13:41
【问题描述】:


我有一个字典“playerDict”,它从一个 plist 中读取数据,其中有名称(myKey),每个键都有九个关联对象。

我正在尝试将特定键 (myKeys) 的所有对象读入 NSMutableArray (theObjects)。我已经阅读了课程参考并搜索了互联网,但无法解决我们这个可能非常简单的问题。

在我完成的所有其他测试中,我尝试了以下方法,但将密钥返回到对象而不是对象中。

theObjects = [playerDict objectForKey:myKeys];

谁能给个提示?

这是创建 dict 的代码,我将其剥离:

NSArray *objs = [NSArray arrayWithObjects:[NSNumber numberWithBool:playerObject.diffHard],[NSNumber numberWithBool:playerObject.diffMedium],
             [NSNumber numberWithBool:playerObject.diffEasy],[NSNumber numberWithBool:playerObject.currentGame],
             [NSNumber numberWithInt:playerObject.currentGameQuestion],[NSNumber numberWithInt:playerObject.currentGameRightAnswer],
             [NSNumber numberWithInt:playerObject.currentGameType],[NSNumber numberWithInt:playerObject.nrOfType0Games],
             [NSNumber numberWithInt:playerObject.type0Result], nil];
NSDictionary *newPlayerDict = [NSDictionary dictionaryWithObjectsAndKeys:objs, keyString, nil];

【问题讨论】:

    标签: iphone objective-c nsdictionary


    【解决方案1】:

    试试valueForKey:

    【讨论】:

    • 我不知道我之前在 valueForKey 上做错了什么,但现在它终于起作用了。非常感谢你们所有人。也许就像我因为树木而看不到阿甘:-)
    【解决方案2】:

    每个密钥只能在NSDictionary 中存储一项。如果您需要同一键的多个项目,则需要先将每个项目添加到 NSArray(或 NSSet),然后将其设置为字典中的对象。

    如果您发布创建字典的代码可能会有用。

    更新:您似乎已经在这样做了。所以:

    NSArray *myObjs=[playerDict objectForKey:keyString];
    

    会给你你的阵列。还有这个:

    BOOL diffHard=[[myObjs objectAtIndex:0] boolValue];
    BOOL diffMedium=[[myObjs objectAtIndex:1] boolValue];
    

    将为您获取存储在数组的第一个和第二个对象中的值。其余部分重复。

    【讨论】:

      猜你喜欢
      • 2021-03-17
      • 1970-01-01
      • 2022-08-03
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-26
      • 2022-06-16
      相关资源
      最近更新 更多