当一些键的动态变化时,如何从字典中获取值

时间:2014-04-25 07:34:17

标签: ios objective-c nsdictionary

我有一个包含20个对象的Mutable数组。每个对象都有给定的格式

{

 "NONE-NONE-ABCD-RECD" =     {
  Count =         
        {
              bird = "10";
              animal = "4";
        };

  Type = "NONE-NONE-ABCD-RECD";
};

} 

对于不同的对象,密钥NONE-NONE-ABCD-RECD会有所不同。有些时候变为 NONE-NONE-NONE-NONE ABCD-PQWE-MNBW-POWE ,等等我需要找到每只物体的鸟和动物。当钥匙变化时,我怎么能得到计数。

2 个答案:

答案 0 :(得分:1)

试试这个,

NSArray *allKeys = [elementDict allKeys]; //elementDict array object
if ([allKeys count] > 0) {
    NSDictionary *objectDict = [elementDict objectForKey:[allKeys objectAtIndex:0]];
    NSDictionary *countDict = [objectDict objectForKey:@"Count"];
    //from countDict you can access values
    NSString *bird = [countDict valueForKey:@"bird"];
    NSString *animal = [countDict valueForKey:@"animal"];
}

答案 1 :(得分:0)

好吧,如果Type每次都会返回key,那么你可以这样做:

NSString *yourKey = [yourDictionary objectForKey:@"Type"];
NSDictionary *countDict = [yourDictionary objectForKey:yourKey];
int bird = [[countDict objectForKey:@"bird"] intValue];
int animal = [[countDict objectForKey:@"animal"] intValue];

其他解决方案:

for (NSString *aKey in yourDictionary)
{
    if ([[yourDictionary objectForKey:@"aKey"] isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *countDict = [yourDictionary objectForKey:aKey];
        int bird = [[countDict objectForKey:@"bird"] intValue];
        int animal = [[countDict objectForKey:@"animal"] intValue];
    }
}

其他解决方案,如果您的对象可能包含其他子词典:

for (NSString *aKey in yourDictionary)
{
    if ([[yourDictionary objectForKey:@"aKey"] objectForKey:@"Count"])
    {
        NSDictionary *countDict = [[yourDictionary objectForKey:@"aKey"] objectForKey:@"Count"];
        int bird = [[countDict objectForKey:@"bird"] intValue];
        int animal = [[countDict objectForKey:@"animal"] intValue];
    }
}