iPhone Multithreaded Search
- by Kulpreet
I'm sort of new to any sort of multithreading and simply can't seem to get a simple search method working on a background thread properly. Everything seems to be in order with an NSAutoreleasePool and the UI being updated on the main thread. The app doesn't crash and does perform a search in the background but the search results yield the several of the same items several times depending on how fast I type it in. The search works properly without the multithreading (which is commented out), but is very slow because of the large amounts of data I am working with. Here's the code:
- (void)filterContentForSearchText:(NSString*)searchText {
isSearching = YES;
NSAutoreleasePool *apool = [[NSAutoreleasePool alloc] init];
/*
Update the filtered array based on the search text and scope.
*/
//[self.filteredListContent removeAllObjects]; // First clear the filtered array.
for (Entry *entry in appDelegate.entries)
{
NSComparisonResult result = [entry.gurmukhiEntry compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame)
{
[self.filteredListContent addObject:entry];
}
}
[self.searchDisplayController.searchResultsTableView performSelectorOnMainThread:(@selector(reloadData)) withObject:nil waitUntilDone:NO];
//[self.searchDisplayController.searchResultsTableView reloadData];
[apool drain];
isSearching = NO; }
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
if (!isSearching) {
[self.filteredListContent removeAllObjects]; // First clear the filtered array.
[self performSelectorInBackground:(@selector(filterContentForSearchText:)) withObject:searchString];
}
//[self filterContentForSearchText:searchString];
return NO; // Return YES to cause the search result table view to be reloaded. }