在背景线程上搜索 [英] Searching on a Background Thread
本文介绍了在背景线程上搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在我的iPhone应用程序中搜索几千个对象,但是搜索严重滞后 - 每次击键后UI都会冻结1-2秒。为了防止这种情况,我必须在后台线程上执行搜索。
I am trying to search through a few thousand objects in my iPhone app, however the search lags badly - after each keystroke the UI freezes for 1 - 2 seconds. To prevent this, I have to execute the search on a background thread.
我想知道是否有人在后台线程上搜索一些提示?我读了一下 NSOperation
并在网上搜索,但没有找到任何有用的东西。
I was wondering whether anyone had some tips for searching on a background thread? I read a little into NSOperation
and searched the web, but didn't really find anything useful.
推荐答案
尝试使用 NSOperationQueue
作为视图控制器中的实例变量。
Try using an NSOperationQueue
as an instance variable in your view controller.
@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
这篇关于在背景线程上搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文