开发者

get key by name from NSDictionary

开发者 https://www.devze.com 2023-02-10 18:05 出处:网络
I have a nested NSDictionary of NSDictionaries. I get the dictionaries in an NSArray *array and I iterate through them with for (NSDictionary *frame in array)

I have a nested NSDictionary of NSDictionaries. I get the dictionaries in an NSArray *array and I iterate through them with for (NSDictionary *frame in array)

What I want is the name of the frame. For example [frame getName], is there any 开发者_运维百科function for this?


If your array looks like this

<array>
    <dict>
        <key>name</key>
        <string>My First Frame</string>
        ...
    </dict>
    <dict>
        <key>name</key>
        <string>My Other Frame</string>
        ...
    </dict>
    ...
</array>

Then you would use this to get the name:

for (NSDictionary *frame in array) {
    NSString *frameName = [frame objectForKey:@"name"];
}

However, if your dictionaries do not actually contain your frame's name, then you're out of luck (in an array, elements are stored using an index, not with a key).

Now, you've also referred to "nested NSDictionaries of NSDictionaries" above. If you have for example the following structure, where the name is the key in the outer dictionary:

<dict>
    <key>My First Frame</key>
    <dict>
        <key>width</key>
        <integer>300</integer>
        <key>height</key>
        <integer>200</integer>
        ...
    </dict>
    <key>My Second Frame</key>
    <dict>
        <key>width</key>
        <integer>150</integer>
        <key>height</key>
        <integer>105</integer>
        ...
    </dict>
    ...
</dict>

Then you could use this:

for (NSString *frameName in [outerDict allKeys]) {
    NSDictionary *frame = [outerDict objectForKey:frameName];
    // now you have both the key (frameName) and the value (frame) to work with
}


Not fully understand your question, do you mean to get object from Dictionary by Key

[dict objectForKey:@"key"] should got it.

And if you means have another array which stores all the sub dictionary objects, and you need know the specify sub-dictionary's key value in the root dictionary:

[[rootDict allKeysForObject:theSpecifySubDictionary] lastObject]


NSArray *myTemp2Array = [myArray valueForKey:@"Name"];

This will walk an array (that contains dictionaries) and return all the values for the @"Name" key in a nice little array.

0

精彩评论

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