我的iphone应用程序显示了一个包含6000项列表的表视图。(这些项目在SQLite文件中)
用户可以搜索这些项目。但是,当我点击搜索栏并开始输入第一个字母时,我需要很长时间才能输入第二个字母。同样,在我开始搜索之前,输入每个字母也需要很长时间。
有没有办法提高搜索工具栏的输入速度,以便用户可以快速输入5-6个字母进行搜索?
我很感谢你的帮助。谢谢!
发布于 2010-11-17 02:38:06
如果您的搜索速度太慢,从而阻塞了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];
现在,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];
}
现在,自定义方法searchDidFinishWithResult:
负责使用搜索结果更新UI:
- (void)searchDidFinishWithResult:(NSArray *)searchResult
{
// Update the UI with the search results
...
}
这可能是最简单的开始方法。解决方案还没有完成,部分原因是如果用户输入的速度快于搜索的完成速度,搜索任务就会堆积如山。您可能应该加入一个空闲计时器,该计时器会等待一段时间,直到启动搜索,或者您需要取消正在进行的搜索任务(在这种情况下,NSOperation
可能更好)。
发布于 2010-11-17 02:40:25
而不是在每次调用"textDidChange“时搜索整个列表,而是只在调用"searchBarSearchButtonClicked”时搜索吗?
您可能会丢失自动更新,但它不会造成每次都会出现的延迟。
发布于 2010-11-17 14:34:47
我不知道您的表是否已编入索引。如果没有,您应该为表创建一个索引。表的更新会更慢,但搜索应该更快。祝好运。
https://stackoverflow.com/questions/4197633
复制相似问题