我的字典设置如下。如何从objectAtIndex:1
获取实际键值(演员姓名)?
<plist version="1.0">
<dict>
<key>Brad Pitt</key>
<array>
<string>Fight Club</string>
<string>Seven</string>
<string>Inglorious Basterds</string>
<string>Babel</string>
</array>
<key>Meryl Streep</key>
<array>
<string>Adaptation</string>
<string>The Devil Wears Prada</string>
<string>Doubt</string>
<string>Julie & Julia</string>
</array>
<key>Chris Cooper</key>
<array>
<string>Adaptation</string>
<string>American Beauty</string>
<string>The Bourne Identity</string>
<string>October Sky</string>
</array>
</dict>
</plist>
答案 0 :(得分:5)
蛮力:
- (NSString *)actorForFilm:(NSString *)film {
NSDictionary * dictionary = ...; //your dictionary as read from the plist
for (NSString * actorName in dictionary) {
NSArray * films = [dictionary objectForKey:actorName];
if ([films containsObject:film]) {
return actorName;
}
}
return nil;
}
如果要从字典中返回随机密钥,可以执行以下操作:
NSArray * allKeys = [dictionary allKeys];
NSString * randomKey = [allKeys objectAtIndex:(arc4random() % [allKeys count])];
答案 1 :(得分:1)
字典不是有序的,因此objectAtIndex:
类中没有NSDictionary
方法。如果要将演员/电影对存储在有序列表中,则需要将它们存储在NSArray中,例如使用如下结构:
# pseudo-code: [] = array, {} = dictionary
[
{ actor: "Brad Pitt", movies: ["Fight Club", "Seven", "Babel"] },
{ actor: "Meryl Streep", movies: ["Adaptation", "Doubt"] },
# etc...
]
答案 2 :(得分:1)
我觉得你在找这样的东西?
NSString *actorName = [[actorsDictionary allKeys] objectAtIndex:index];