Searching on a Background Thread

Deadly 提交于 2019-12-21 01:46:06

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/4421181/searching-on-a-background-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!