调整iPhone TableSearch算法防止UI延迟

时间:2009-07-29 02:03:24

标签: iphone cocoa-touch

我的大部分代码都基于Apple的TableSearch示例,但是我的应用程序包含35,000个需要搜索的单元格而不是示例中的少数单元格。关于UISearchDisplayController的在线文档不多,因为它相对较新。我使用的代码如下:

- (void)filterContentForSearchText:(NSString*)searchText {
/*
 Update the filtered array based on the search text and scope.
 */

[self.filteredListContent removeAllObjects]; // First clear the filtered array.

/*
 Search the main list for products whose type matches the scope (if selected) and whose name matches searchText; add items that match to the filtered array.
 */
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
for (Entry *entry in appDelegate.entries)
{
    if (appDelegate.searchEnglish == NO) {
        NSComparisonResult result = [entry.gurmukhiEntry compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
        if (result == NSOrderedSame)
        {
            [self.filteredListContent addObject:entry];
        }
    }
    else {
        NSRange range = [entry.englishEntry rangeOfString:searchText options:NSCaseInsensitiveSearch];
        if(range.location != NSNotFound)
        {
            [self.filteredListContent addObject:entry];
        }

    }
}}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterContentForSearchText:searchString];
[self.view bringSubviewToFront:keyboardView];

// Return YES to cause the search result table view to be reloaded.
return YES;}

我的问题是在键盘上按下每个按钮后会有一点延迟。这成为一个可用性问题,因为当用户在数组中搜索匹配结果时,用户必须在输入每个字符后等待。如何调整此代码,以便用户可以连续输入而不会有任何延迟。在这种情况下,可以延迟数据重新加载所需的时间,但它不应该在键入时阻止键盘。

1 个答案:

答案 0 :(得分:0)

更新

在没有“锁定”UI的情况下进行搜索时完成搜索的一种方法是使用线程。

因此,您可以使用此方法调用执行排序的方法:

- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg

这将使其脱离主线程,允许UI更新。

您必须在后台线程上创建并耗尽自己的Autorealease池。

但是,当您想要更新表时,您必须回复主线程(所有UI更新必须在主线程上):

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait

您还可以通过使用NSOperation / NSOperationQueue或NSThread获得更多控制权。

请注意,实现线程充满了危险。您必须确保您的代码是线程安全的,并且您可能会得到不可预测的结果。

此外,以下是其他可能有用的stackoverflow答案:

Using NSThreads in Cocoa?

Where can I find a good tutorial on iPhone/Objective-C multithreading?


原始答案:

在用户按下“搜索”按钮之前,请勿执行搜索。

您可以实现一种委托方法来捕捉按下搜索按钮:

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar;