开发者

Get the key from a dictionary object?

I have a dictionary开发者_如何转开发 set up like the one below. How can I get the actual key value (the actor's name) from 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 &amp; 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>


Brute force it:

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

If you want to return a random key from the dictionary, you could do:

NSArray * allKeys = [dictionary allKeys];
NSString * randomKey = [allKeys objectAtIndex:(arc4random() % [allKeys count])];


I think you're looking for something like this?

NSString *actorName = [[actorsDictionary allKeys] objectAtIndex:index];


Dictionaries aren't ordered, so there is no objectAtIndex: method in the NSDictionary class. If you want to store the actor/film pairs in an ordered list you need to store them in an NSArray, for example using a structure like this:

# pseudo-code: [] = array, {} = dictionary
[
    { actor: "Brad Pitt", movies: ["Fight Club", "Seven", "Babel"] },
    { actor: "Meryl Streep", movies: ["Adaptation", "Doubt"] },
    # etc...
]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜