fabian789 fabian789 - 1 year ago 86
iOS Question

Searching on a Background Thread

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

and searched the web, but didn't really find anything useful.

Answer Source

Try using an NSOperationQueue as an instance variable in your view controller.

@interface SearchViewController : UIViewController {
    NSOperationQueue *searchQueue;
    //other awesome ivars...
//blah blah

@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 
   [searchQueue addOperation:op];
   [op release];  

- (void) dealloc {
  [searchQueue release];
  [super dealloc];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download