Search code examples
objective-cxcodensarraynspredicate

Why does NS predicate failing to parse my conditional statement on NSArray Index


I am retrieving web data via an api, using jsonSerialization.

NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: responseData options: NSJSONReadingMutableContainers error: &e]; 

Then I am able to get desired data using following predicate.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"value == 1 && day = 0"]; 
NSArray *filteredArray = [[jsonArray filteredArrayUsingPredicate:predicate] valueForKey:@"hour"];

This gives me an filteredArray of the data I want.

filteredArray = ( 0, 1, 2, 7, 8, 9, 14, 15, 16, 17 )

From this filteredArray I need to extract start and end of all the continuous numbers. For example in the above array these are (0, 2, 7, 9, 14, 18). I am trying to achieve this using second predicate on my filteredArray, by passing the array index as condition.

 NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"if (filteredArray[1] - filteredArray[0] !=0)"]; 

This is crashing my program. I thought I can pass the array index that way to a predicate ?


Solution

  • NSPredicate is the wrong API to filter ranges.

    I recommend to convert the indexes to NSIndexSet and enumerate the ranges

    NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
    for (NSNumber *index in filteredArray) {
        [indexSet addIndex:index.unsignedIntegerValue];
    }
    [indexSet enumerateRangesUsingBlock:^(NSRange range, BOOL * _Nonnull stop) {
         NSLog(@"%ld, %ld", range.location, range.length);
    }];