如何提高Iphone SDK的搜索速度

mee*_*tpd 3 iphone objective-c iphone-sdk-3.0 ios4

我的iphone App显示了一个包含6000个项目列表的表格视图.(这些项目在SQLite文件中)

用户可以搜索这些项目.但是,当我点击搜索栏并开始输入第一个字母时,我需要很长时间才能输入第二个字母.同样,在我开始搜索之前输入每个字母需要很长时间.

有没有办法提高搜索工具栏的打字速度,以便用户可以快速输入5-6个字母进行搜索?

我感谢您的帮助.谢谢!

Ole*_*ann 6

如果您的搜索太慢并因此阻止了UI,则应异步执行搜索,以免阻塞主线程.要做到这一点,有很多选择,包括大中央调度(4.0+), ,.NSOperation performSelectorInBackground:...最适合您的方法取决于您的应用程序/算法的架构以及您最熟悉的内容.

编辑:启动,文档阅读performSelectorInBackground:withObject:performSelectorOnMainThread:withObject:waitUntilDone:.从搜索栏委托方法,尝试调用类似于:

 // -searchForString: is our search method and searchTerm is the string we are searching for
 [self performSelectorInBackground:@selector(searchForString:) withObject:searchTerm];
Run Code Online (Sandbox Code Playgroud)

现在Cocoa将创建一个后台线程并-searchForString:在该线程上调用您的自定义方法.这样,主线程将不会被阻止.自定义方法应如下所示:

- (void)searchForString:(NSString *)searchTerm
{
    // First create an autorelease pool (we must do this because we are on a new thread)
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // Perform the search as you normally would
    // The result should be an array containing your search results
    NSArray *searchResults = ...

    // Pass the search results over to the main thread
    [self performSelectorOnMainThread:@selector(searchDidFinishWithResult:) withObject:searchResults waitUntilDone:YES];

    // Drain the ARP
    [pool drain];
}
Run Code Online (Sandbox Code Playgroud)

现在,自定义方法searchDidFinishWithResult:负责使用搜索结果更新UI:

- (void)searchDidFinishWithResult:(NSArray *)searchResult
{
    // Update the UI with the search results
    ...
}
Run Code Online (Sandbox Code Playgroud)

这可能是一个开始最简单的方法.解决方案还没有完成,部分原因是如果用户输入的速度比搜索完成的速度快,搜索任务就会堆积起来.您可能应该合并一个等待一段时间的空闲计时器,直到搜索被触发,或者您需要取消正在进行的搜索任务(NSOperation在这种情况下可能更好).