我正在实现一个根据用户输入的文本过滤UITableView的搜索字段。
该TableView中被从保持NSString的(要显示的数据和搜索),并且可以含有6000+项阵列建立。
当用户开始搜索时,我正在执行-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
方法。
在大阵列中搜索字符串需要很长时间
但是,我的代码工作,但是,当数据数组很大,它非常缓慢,并创建了一个非常糟糕的用户体验(我的iPhone 4卡住了好几秒钟)。
我执行搜索(在上面提到的方法)的方法是这样的:
NSMutableArray *discardedItems = [[NSMutableArray alloc] init]; // Items to be removed
searchResultsArray = [[NSMutableArray alloc] initWithArray:containerArray]; // The array that holds all the data
// Search for matching results
for (int i=0; i<[searchResultsArray count]; i++) {
NSString *data = [[containerArray objectAtIndex:i] lowercaseString];
NSRange r = [data rangeOfString:searchText];
if (r.location == NSNotFound) {
// Mark the items to be removed
[discardedItems addObject:[searchResultsArray objectAtIndex:i]];
}
}
// update the display array
[searchResultsArray removeObjectsInArray:discardedItems];
[myTableView reloadData];
我没想到的是遍历数组有几千个项目将造成任何问题。 ..
任何建议将不胜感激!
UPDATE 我刚刚意识到什么需要的大部分时间是这样的:
[searchResultsArray removeObjectsInArray:discardedItems];
仪器说什么? –
你尝试过排序,然后使用二进制搜索? – Samir
排序是不可能的,因为:1.我需要按照数组中的原始顺序对结果进行排序。 2.我正在查找数组中每个项目的子字符串,而不是它开头的字符串。所以,排序不会有帮助... –