Search code examples
iosobjective-cnsarraynsdictionarynspredicate

NSPredicate on nested array with NSDictionary as object


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.


Solution

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