NSPredicate on nested array with NSDictionary as object

心已入冬 提交于 2020-02-16 05:25:49

问题


i have a NSDictionary like:

{
"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";
    }
);
}

i'm trying to apply

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

it use to work when i had structure something like

array > dictionary

but now it's like

array > array > dictionary

by doing [dic allValues] for array. any help what should i apply to keep it fast.


回答1:


What you need to do is need enumerate your dictionary and create new filtered Dictionary.

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;
     }
}];



回答2:


Try this :

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


来源:https://stackoverflow.com/questions/43739514/nspredicate-on-nested-array-with-nsdictionary-as-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!