Get the key to the dictionary object?

I have a dictionary like the one below. How can I get the actual key value (actor 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>
+3
source share
3 answers

I think you are looking for something like this?

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

Probably:

- (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 can do:

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

Dictionaries are not ordered, so there is NSDictionaryno method objectAtIndex:. If you want to save actor / movie pairs in an ordered list, you need to save them in NSArray, for example, using the following structure:

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

Source: https://habr.com/ru/post/1783025/


All Articles