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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With