1

我有一个视图,上面有 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";
        };
    };
}

我如何获得这些值中的每一个?谢谢。

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

4

3 回答 3

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);
    }
}
于 2012-11-14T06:39:40.283 回答
1
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];

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

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

于 2012-11-14T06:27:27.207 回答
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...
}];
于 2014-10-24T12:43:20.353 回答