在我的应用程序中,我有一个大约20,000个项目的大表。我在tableview上显示它。但是在进行动态搜索时搜索栏太慢了。我已经读过NSPredicate方法比NSRange高性能。 我不知道如何应用这种方法。
我的代码是:
- (void)filterContentForSearchText:(NSString*)searchText
{
[self.filteredListContent removeAllObjects];
for (Book *book in listContent)
{
NSRange range = [book.name rangeOfString:searchText options:NSCaseInsensitiveSearch];
// is very very slow
if (range.location != NSNotFound)
{
[self.filteredListContent addObject:book];
}
}
}
我必须将NSPredicate插入我们的“for”中吗?
答案 0 :(得分:2)
- (void)filterContentForSearchText:(NSString*)searchText
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains %@", searchText ];
self.filteredListContent = [NSMutableArray arrayWithArray:[listContent filteredArrayUsingPredicate:predicate]];
}
答案 1 :(得分:2)
如果过滤例如NSArray,您可以使用
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"job == 'Programmer'"]
[listOfItems filterUsingPredicate:predicate];
如果您想使用
进行获取请求NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title == %@", aTitle];
[request setEntity:[NSEntityDescription entityForName:@"DVD" inManagedObjectContext:moc]];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];
// error handling code
[request release];
编辑:
[NSPredicate predicateWithFormat:@"name contains[cd] %@", searchString];