2010-12-12 10 views
6

iPhoneアプリで数千のオブジェクトを検索しようとしていますが、キーストロークが終わるごとに1〜2秒間画面がフリーズします。これを防ぐには、バックグラウンドスレッドで検索を実行する必要があります。バックグラウンドスレッドで検索する

誰かがバックグラウンドスレッドで検索するためのヒントを持っていたかどうかは分かりませんでしたか?私は少しだけNSOperationを読んで、ウェブを検索しましたが、実際に役に立たないものは何も見つかりませんでした。

答えて

6

ビューコントローラでNSOperationQueueをインスタンス変数として使用してみてください。

@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

ありがとうございます。-beginSearch内の検索はうまくいくようですが、私の結果を元の配列に戻すことはできません(私の 'UITableView'に使用しています)...?別のスレッドから割り当てることはできませんか? – fabian789

+0

@ fabian789ハングアップ、私の答えを編集しましょう... –

+0

私はそうしました: '[self performSelectorOnMainThread:@selector(updateArray :) withObject:tmp_filter waitUntilDone:NO]'を呼び出し、 '[self.searchDisplayController.searchResultsTableView reloadData] 'を' updateArray'から削除します。あなたの解決策を見て好奇心... – fabian789

関連する問題