NSPredicate在嵌套数组上使用NSDictionary作为对象

时间:2017-05-02 13:43:41

标签: ios objective-c nsarray nsdictionary nspredicate

我有一个类似的NSDictionary:

{
"2017-05-02" =     (
            {
        "always_valid" = 0;
        date = "2017-05-02";
        from = "12:00";
        to = "13:00";
    },
            {
        "always_valid" = 0;
        date = "2017-05-02";
        from = "12:00";
        to = "12:00";
    },
            {
        "always_valid" = 0;
        date = "2017-05-02";
        from = "14:00";
        "hourly_rate" = 12;
        to = "15:00";
    }
);
"2017-05-03" =     (
            {
        "always_valid" = 0;
        date = "2017-05-03";
        from = "12:00";
        to = "13:00";
    }
);
"2017-05-18" =     (
            {
        "always_valid" = 1;
        date = "2017-05-18";
        from = "12:00";
        to = "12:00";
    }
);
}

我正在尝试申请

NSPredicate *filter = [NSPredicate predicateWithFormat:@"always_valid = \"1\""];
 NSArray *alwaysvalid = [[dic allValues] filteredArrayUsingPredicate:filter];

当我有像

这样的结构时,它可以用来工作

数组>字典

但现在就像

数组>数组>字典

为数组做[dic allValues]。 任何帮助我应该用什么来保持它快。

2 个答案:

答案 0 :(得分:2)

您需要做的是枚举您的词典并创建新的过滤词典。

NSMutableDictionary *filterDic = [[NSMutableDictionary alloc] init];
NSPredicate *filter = [NSPredicate predicateWithFormat:@"always_valid = 1"];
[dict enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSArray* obj, BOOL *stop) {
     NSArray *filterArray = [obj filteredArrayUsingPredicate:filter];
     if (filterArray.count > 0) {
         filterDic[key] = filterArray;
     }
}];

答案 1 :(得分:-1)

试试这个:

 NSArray *array = [NSArray arrayWithObject:dict];   // you can also do same for Name key... 
 NSArray *alwaysvalid = [array filteredArrayUsingPredicate:filter];