Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 NSOperation and searched the web, but didn't really find anything useful.

like image 384
fabian789 Avatar asked Dec 12 '10 10:12

fabian789


1 Answers

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
like image 80
Jacob Relkin Avatar answered Oct 25 '22 06:10

Jacob Relkin