我试图在 iPhone 应用程序中搜索数千个对象,但是搜索严重滞后 - 每次击键后 UI 都会冻结 1 - 2 秒。为了防止这种情况,我必须在后台线程上执行搜索。
我想知道是否有人有一些在后台线程上搜索的提示?我读了一点NSOperation
并在网上搜索,但并没有真正找到任何有用的东西。
尝试使用NSOperationQueue http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperationQueue_class/Reference/Reference.html作为视图控制器中的实例变量。
@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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)