Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableArray filterUsingPredicate only past a certain index

I'm attempting to cull my NSMutableArray of elements with filterUsingPredicate.

The tricky part is that I always want to keep at least 10 items in the array, regardless if whether they pass the predicate test. So something like:

NSPredicate * cullPredicate = [NSPredicate predicateWithFormat:
        @"distanceFromCurrent <= 25 OR index < 10"];

[self.myArray filterUsingPredicate:cullPredicate];

The 'OR index < 10' as an indication of what I'd like to do... I realize it won't work.

Is this possible with predicates? Or do I need to pull out another array with elements starting at 10, apply the filter, and then add it back onto the original array?

like image 586
Richard Lovejoy Avatar asked Feb 21 '23 11:02

Richard Lovejoy


1 Answers

NSPredicate has a -predicateWithBlock: method that you can use to do this. Something like this:

NSArray *array = [[self.myArray copy] autorelease];
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {        
    if ([array indexOfObject:evaluatedObject] < 10) return YES;
    return evaluatedObject.distanceFromCurrent <= 25;
}];
[self.myArray filterUsingPredicate:predicate];
like image 151
Andrew Madsen Avatar answered Mar 07 '23 08:03

Andrew Madsen