4

I am trying to limit array of objects getting with [NSArray filteredArrayUsingPredicate] for better performance.

My Code:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.Name contains[c] %@", searchText]; 
NSArray *filteredArray = [self.dataArray filteredArrayUsingPredicate:predicate];

My dataArray contains about 30.000 objects and I want to limit result array 50. (I need some break statement after 50 match found.) How can I achieve this?

4

2 回答 2

5

Use simple for-in loop, NSMutableArray builder and -[NSPredicate evaluateWithObject:] method.

NSMutableArray *builder = [NSMutableArray arrayWithCapacity:50];
for (id object in array) {
    if ([predicate evaluateWithObject:object]) {
        [builder addObject:object];
        if (builder.count >= 50) break;
    }
}

I noticed you tagged the question by Core Data. If you can use NSFetchRequest, then just set its fetchLimit to 50.

于 2013-07-05T11:24:44.880 回答
1

How about this?

myArray = [originalArray filteredArrayUsingPredicate:myPredicate];

if ([myArray count] > resultLimit) {
        myArray = [myArray subarrayWithRange:NSMakeRange(0, resultLimit)];
}
于 2014-08-29T17:30:06.123 回答