objective-c - 在后台线程上搜索

标签 objective-c multithreading ios thread-safety

我试图在我的 iPhone 应用程序中搜索几千个对象,但是搜索非常滞后 - 每次按键后,UI 会卡住 1 - 2 秒。为防止这种情况,我必须在后台线程上执行搜索。

我想知道是否有人有一些关于在后台线程上搜索的技巧?我读了一点 NSOperation 并在网上搜索,但没有找到任何有用的东西。

最佳答案

尝试使用 NSOperationQueue作为 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

关于objective-c - 在后台线程上搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4421181/

相关文章:

java - 通过观察者从线程使用列表中仅获取最新元素

c# - 线程池多客户端 TCP(消息处理)

ios - 何时释放 CGMutablePathRef

ios - OCMock 能否模拟一个类,使其自动在被测代码中使用模拟实例而不注入(inject)它

ios - 没有 iTunes 连接就无法找到待售应用程序

ios - 最佳实践 : ListView - DetailView. 加载更多结果

iphone - 如何获取 MKMapView map 的中心?

iphone - NSInvalidArgumentException 原因 :-[CLLocation distanceFromLocation:]

c# - 从同一线程内部中止线程

ios - 如何在 NSArray 中创建 NSDictionary 以及如何在 ios 中访问它们