iOS UISearchBar如何正确实现“按键搜索”行为?

时间:2014-06-09 14:23:44

标签: ios json uitableview uisearchbar nspredicate

我在iPad上使用分割视图控制器实现搜索功能。它搜索我从JSON对象获得的NSDictionary数组。

我在表格视图的标题视图中添加了一个搜索栏,并使用下面的代码用搜索结果更新表格,因为用户正在搜索栏中输入搜索查询。

我很感兴趣如果我正在做的是正确的实施方式"搜索时输入" iOS上的行为?如果我的JSON返回1000个结果,是否会遇到性能问题?我是否需要实现搜索结果控制器而不是仅将搜索栏放入表格视图标题?

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self doSearchWithString:searchText];
}


- (void)doSearchWithString:(NSString*)searchString
{
    NSPredicate* predicate = [NSPredicate predicateWithBlock:^BOOL(NSDictionary *object, NSDictionary *bindings) {
                                  //get the value from the dictionary (the name value)
                                  NSString *name = [object objectForKey:@"name"];

                                  if([[name lowercaseString] rangeOfString:[searchString lowercaseString]].location != NSNotFound) {
                                      return YES;
                                  }
                                  return NO;
                              }];

//change the datasource and ask the table to refresh itself
    self.searchResults = [self.dataSource filteredArrayUsingPredicate:predicate];
    [self.tableView reloadData];
}

1 个答案:

答案 0 :(得分:4)

根据数据集大小,您可能很难通过Core Data获得足够的性能。

可能值得预取然后尝试二进制数组搜索。参见:

How to perform binary search on NSArray?

否则,它可能需要自定义二进制索引,例如Directed Acyclic Word Graph。看看这个答案:

auto complete a search