开发者

Searching on a Background Thread

开发者 https://www.devze.com 2023-01-30 07:59 出处:网络
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 sea

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 an开发者_开发知识库ything 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号