我试图在我的iPhone应用程序中搜索几千个对象,但是搜索严重滞后 - 每次击键后UI都会冻结1-2秒。为了防止这种情况,我必须在后台线程上执行搜索。
我想知道是否有人在后台线程上搜索一些提示?我读了一下NSOperation
并搜索了网页,但没有找到任何有用的东西。
答案 0 :(得分:6)
尝试在视图控制器中使用NSOperationQueue
作为实例变量。
@interface SearchViewController : UIViewController {
NSOperationQueue *searchQueue;
//other awesome ivars...
}
//blah blah
@end
@implementation SearchViewController
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle {
if((self = [super initWithNibName:nibName bundle:nibBundle])) {
//perform init here..
searchQueue = [[NSOperationQueue alloc] init];
}
return self;
}
- (void) beginSearching:(NSString *) searchTerm {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//perform search...
[self.searchDisplayController.searchResultsTableView reloadData];
[pool drain];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
/*
Cancel any running operations so we only have one search thread
running at any given time..
*/
[searchQueue cancelAllOperations];
NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(beginSearching:)
object:searchText];
[searchQueue addOperation:op];
[op release];
}
- (void) dealloc {
[searchQueue release];
[super dealloc];
}
@end