调整iPhone表搜索算法以防止UI延迟

调整iPhone表搜索算法以防止UI延迟,iphone,cocoa-touch,Iphone,Cocoa Touch,我的大部分代码都基于Apple的TableSearch示例,但是我的应用程序包含35000个需要搜索的单元格,而不是示例中的少数单元格。关于UISearchDisplayController的在线文档并不多,因为它相对较新。我使用的代码如下: - (void)filterContentForSearchText:(NSString*)searchText { /* Update the filtered array based on the search text and scope. */

我的大部分代码都基于Apple的TableSearch示例,但是我的应用程序包含35000个需要搜索的单元格,而不是示例中的少数单元格。关于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;}
我的问题是,在按下键盘上的每个按钮后都会有一点延迟。这成为一个可用性问题,因为当应用程序在数组中搜索匹配结果时,用户必须在键入每个字符后等待。如何调整此代码,以便用户可以连续键入而不出现任何延迟。在这种情况下,数据重新加载所需时间的延迟是可以的,但它不应在键入时挡住键盘

更新:

在不“锁定”用户界面的情况下,在键入时完成搜索的一种方法是使用线程

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

- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg
这将使它远离主线程,从而允许UI更新

您必须在后台线程上创建并耗尽自己的自动恢复池

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

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

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

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


原始答复:

在用户按下“搜索”按钮之前,不要执行搜索

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

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

不完全是我要找的…我以前见过这样做,用户键入,加载表时有延迟,但它与键盘分离,可以自由键入大型数据库。我只是更新了我的答案,可能更相关
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar;