1

我有一个 UISearchResultsController 正在过滤我的 NSFetchedResultsController 并将过滤后的数据放入一个数组中。目前,我使用 NSPredicate 获取搜索栏内容并应用过滤器。这是我的谓词:

[filteredArray removeAllObjets];
for(Account *account in unfilteredResults){
NSPredicate *predicate;

if(controller.searchBar.selectedScopeButtonIndex == 0){

  predicate = [NSPredicate predicateWithFormat:@"accountFirstName BEGINSWITH[cd] %@", searchString];
}else if(controller.searchBar.selectedScopeButtonIndex == 1){

  predicate = [NSPredicate predicateWithFormat:@"accountLastName BEGINSWITH[cd] %@", searchString];
}else if(controller.searchBar.selectedScopeButtonIndex == 2){

  predicate = [NSPredicate predicateWithFormat:@"group.groupName CONTAINS[cd] %@", searchString];
}

  if([predicate evaluateWithObject:account]){
    [self.filteredArray addObject:account];
  }
}

我正在尝试根据名字、姓氏或组名过滤帐户。我知道这些操作很慢,但是可以做些什么来让它们更快呢?

编辑:

我只是注意到我每次迭代都在重新创建谓词,但我仍然认为应该有更好的方法。我确实在 Apple 视频中看到了一些关于进行二进制比较的内容,但我不知道如何将搜索字符串转换为二进制字符串,更不知道如何获得“下一个最大”值。

如何用更有效的方法替换 BEGINSWITH 语句?

4

2 回答 2

1

我假设您的数据对象是 CoreData 对象,如果是这样,您是否将要搜索的属性标记为索引?

于 2011-06-29T03:52:39.530 回答
1

这是太旧的帖子,但可以帮助别人。使用此代码,您将只创建一个 NSPredicate 实例。

NSPredicate *predicate;

if(controller,searchBar,.selectedScopeButtonIndex == 0){

  predicate = [NSPredicate predicateWithFormat:@"accountFirstName BEGINSWITH[cd] %@",     searchString];
}else if(controller,searchBar,.selectedScopeButtonIndex == 1){

  predicate = [NSPredicate predicateWithFormat:@"accountLastName BEGINSWITH[cd] %@",     searchString];
}else if(controller,searchBar,.selectedScopeButtonIndex == 2){

  predicate = [NSPredicate predicateWithFormat:@"group.groupName CONTAINS[cd] %@", searchString];
}
self.filteredArray = [unfilteredResults filteredArrayUsingPredicate:predicate];
于 2012-04-18T17:23:18.700 回答