2010-12-12 34 views
6

Tôi đang cố gắng tìm kiếm qua vài nghìn đối tượng trong ứng dụng iPhone của mình, tuy nhiên tìm kiếm chậm quá - sau mỗi lần nhấn phím, giao diện người dùng bị đóng băng trong 1 - 2 giây. Để ngăn chặn điều này, tôi phải thực hiện tìm kiếm trên một chuỗi nền.Tìm kiếm trên một chủ đề nền

Tôi đã tự hỏi liệu có ai có một số mẹo để tìm kiếm trên một chuỗi nền không? Tôi đã đọc một chút vào số NSOperation và đã tìm kiếm trên web nhưng thực sự không tìm thấy gì hữu ích.

Trả lời

6

Thử sử dụng NSOperationQueue làm biến mẫu trong trình điều khiển chế độ xem của bạn.

@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

Cảm ơn, tìm kiếm bên trong -beginTìm kiếm dường như hoạt động, tuy nhiên dường như tôi không nhận được kết quả vào mảng ban đầu (mà tôi sử dụng cho 'UITableView') ...? Không thể chỉ định từ một chuỗi riêng biệt? – fabian789

+0

@ fabian789 Hãy đợi, hãy để tôi chỉnh sửa câu trả lời của mình ... –

+0

Tôi đã làm như vậy: '[self performSelectorOnMainThread: @selector (updateArray :) withObject: tmp_filter waitUntilDone: NO]', sau đó gọi '[self.searchDisplayController.searchResultsTableView reloadData] 'từ' updateArray'. Tò mò để xem giải pháp của bạn ... – fabian789

Các vấn đề liên quan