Ultimate NSPredicate Results

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

My code is:

 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 the result array to 50. (I need some break statement after the match is found.) How can I achieve this?

+4
source share
2 answers

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

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

I noticed that you noted the question of Core Data . If you can use NSFetchRequest , just set its fetchLimit to 50.

+5
source

How about this?

 myArray = [originalArray filteredArrayUsingPredicate:myPredicate]; if ([myArray count] > resultLimit) { myArray = [myArray subarrayWithRange:NSMakeRange(0, resultLimit)]; } 
+1
source

Source: https://habr.com/ru/post/1489885/


All Articles