我从我的数据库peopleArray
获得了一个非常大的数组,其中包含我应用的所有用户。该数组用于搜索朋友。我的问题是,当用户开始在搜索栏中输入时,应用程序通常会在显示搜索到的用户之前暂停一段时间。
#pragma mark - SEARCH BAR
- (void) filterContententForSearchText: (NSString *) searchText scope:(NSString *) scope{
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K beginsWith[cd] %@",@"Name", searchText ];
self.searchArray = [self.peopleArray filteredArrayUsingPredicate:predicate];
}
- (BOOL) searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
[self filterContententForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
- (void) searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller{
[self.tableView reloadData];
}
我想在后台执行此操作,因此我可以在加载时在tableView中放置UIActivityIndicator
,但不确定在后台实现哪个方法或如何实现该方法。
答案 0 :(得分:0)
首先,我建议使用一个计时器,这样你就不会在每个按键上重新加载用户。我这样做:
//I put this in my private @interface
@property (nonatomic, strong) NSTimer *searchTimer;
//Then we have the method called on keypress
- (void)whateverMethodIsCalledOnKeypress {
[self.searchTimer invalidate];
self.searchTimer = nil;
//put some logic that returns out of the function for empty strings etc. here
self.searchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(runSearch) userInfo:nil repeats:NO];
}
- (void)runSearch {
//do whatever you need to run the search this way
//it's only ever done at most once per second
//so fast typists don't overload the processor
}
这里有一些代码可以进行异步过滤。
//Show your activity indicator
dispatch_async(dispatch_get_global_queue(0,0), ^{
//call whatever you need to do on the filtering here
dispatch_async(dispatch_get_main_queue(), ^{
//Hide your activity indicator
[self.tableView reloadData];
});
});