在foreach中获取NSDictionary的值?

时间:2012-11-14 06:03:51

标签: ios json nsdictionary

我有一个视图,其上有tableviewcells,加载了不同的“键值”作为标签。当我点击一个时,我打开另一个视图。但是在这里,我只传递了那个键的字典,例如我会传递这个:

{
    key = Budget;
    value =     {
        "2012 Budget Report" =         {
            active = 0;
            author = "xxxxx xxxxxx";
            date = "October 27, 2012";
            description = "Example";
            dl = "53 downloads";
            email = "xxx@xxxxx.com";
            ext = DOCX;
            fortest = "Tuesday, November 6";
            id = 5;
            subject = budget;
            testdate = "Tuesday, November 6";
            title = "Budget spreadSheet";
        };
        "2005 - 2008 Budget Report" =         {
            active = 0;
            author = "xxxxxxx xxxxx";
            date = "November 3, 2012";
            description = "Example";
            dl = "18 downloads";
            email = "xxxxx@xxxxx.com";
            ext = DOCX;
            title = "Budget report";
        };
    };
}

我如何获得这些值?感谢。

请注意:值数组中的标题可能会更改...可以添加更多,可以删除一个,所以我需要一个通用的解决方案。

3 个答案:

答案 0 :(得分:11)

考虑您传递的字典保存在iDictionary

NSDictionary *iDictionary // Input Dictionary;
NSDictionary *theValues = [NSDictionary dictionaryWithDictionary:[iDictionary valueForKey:@"value"]];

for (NSString *aKey in [theValues allKeys]) {
    NSDictionary *aValue = [theValues valueForKey:aKey];
    NSLog(@"Key : %@", aKey);
    NSLog(@"Value : %@", aValue);

    // Extract individual values
    NSLog(@"Author : %@", [aValue objectForKey:@"author"]);

    // If the titles are dynamic
    for (NSString *aSubKey in [aValue allKeys]) {
        NSString *aSubValue = [aValue objectForKey:aSubKey];

        NSLog(@"SubKey : %@, SubValue = %@", aSubKey, aSubValue);
    }
}

答案 1 :(得分:1)

NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];

NSArray *arrBudget= [jsonDictionary objectForKey:@"Budget"];

所以这里arrBudget将包含所有值。您可以将数组传递给详细视图。

答案 2 :(得分:0)

如果键和对象在“foreach”逻辑中有用,则采用另一种方法:

NSDictionary *dict = @{
    @"key1": @"value1",
    @"key2": @"value2",
    @"key3": @"value3",
};  
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    NSLog(@"Your key : %@", key);
    NSLog(@"Your value : %@", [obj description]);
    // do something...
}];