循环遍历嵌套的NSMutableDictionary并过滤一些项目

时间:2015-02-26 12:58:17

标签: ios objective-c loops nested-loops nsmutabledictionary

我已经被困在这里一段时间尝试很多事情而没有任何成功。 所以我有一个嵌套的字典,如下所示:

{"Div 3 Mellersta G\u00f6taland, herrar": {
    "0": {"awayScore": "0", "homeTeam": "Hestrafors IF", "tempTime": "12:00", "homeScore": "0", "awayTeam": "Gunnilse IS", "time": "90'", "events": []}, 
    "1": {"awayScore": "0", "homeTeam": "Lerums IS", "tempTime": "13:00", "homeScore": "0", "awayTeam": "Skara FC", "time": "44'", "events": []}, 
    "2": {"awayScore": "0", "homeTeam": "Vara SK ", "tempTime": "14:00", "homeScore": "0", "awayTeam": "IFK Falk\u00f6ping FF", "time": "14:00", "events": []}, 
    "3": {"awayScore": "0", "homeTeam": "Holmalunds IF Alings\u00e5s", "tempTime": "15:00", "homeScore": "0", "awayTeam": "Lunden \u00d6ver\u00e5s BK", "time": "15:00", "events": []}, 
    "4": {"awayScore": "0", "homeTeam": "IFK Tidaholm", "tempTime": "16:00", "homeScore": "0", "awayTeam": "S\u00e4vedalens IF", "time": "16:00", "events": []}}, 
"Div 4 A Herrar": {
    "0": {"awayScore": "0", "homeTeam": "SKIF Semberija", "tempTime": "17:00", "homeScore": "0", "awayTeam": "Floda BoIF", "time": "17:00", "events": []}, 
    "1": {"awayScore": "0", "homeTeam": "Partille IF FK", "tempTime": "18:00", "homeScore": "0", "awayTeam": "Kode IF", "time": "18:00", "events": []}, 
    "2": {"awayScore": "0", "homeTeam": "IK Kongah\u00e4lla", "tempTime": "19:00", "homeScore": "0", "awayTeam": "Romelanda UF", "time": "19:00", "events": []}}}

我需要做的是遍历这里的所有项目以访问键/值对时间,如果时间值的值为0 - 90,我想保存它。

这里重要的是结构不会改变。我的意思是说,例如我们对所有项目进行迭代并检查时间值,然后新词典将如下所示:

{"Div 3 Mellersta G\u00f6taland, herrar": {
    "0": {"awayScore": "0", "homeTeam": "Hestrafors IF", "tempTime": "12:00", "homeScore": "0", "awayTeam": "Gunnilse IS", "time": "90'", "events": []}, 
    "1": {"awayScore": "0", "homeTeam": "Lerums IS", "tempTime": "13:00", "homeScore": "0", "awayTeam": "Skara FC", "time": "44'", "events": []}, 
}}

所有其他项目都被过滤掉,因为 Div 3 Mellersta 中的前两项是唯一时间值为0 - 90的项目。

请注意,它应该用Objective-C

编写

谢谢大家!

1 个答案:

答案 0 :(得分:1)

试试此代码

NSMutableDictionary *newDict = [NSMutableDictionary dictionary];
[rootDict enumerateKeysAndObjectsUsingBlock:^(NSString *key1, NSDictionary *dict1, BOOL *stop) {
    [dict1 enumerateKeysAndObjectsUsingBlock:^(NSString *key2, NSDictionary *dict2, BOOL *stop) {
        NSString *time = dict2[@"time"];
        if([time integerValue] >= 0 && [time integerValue] <= 90 && ![time containsString:@":"]) {
            if(!newDict[key1]) {
                newDict[key1] = [NSMutableDictionary dictionary];
            }
            newDict[key1][key2] = dict2;
        }
    }];
}];