我正在实现一个搜索字段,它根据用户输入的文本过滤 UITableView。
TableView 由一个包含 NSString(要显示和搜索的数据)的数组构建而成,可能包含 6000 多个项目。
当用户开始搜索时,我正在实现 -(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
方法。
我的代码可以工作,但是,当数据数组很大时,它会非常慢并且会造成非常糟糕的用户体验(我的 iPhone 4s 会卡住好几秒钟)。
我实现搜索的方式(在上面提到的方法中)是这样的:
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];
我不认为遍历包含几千项的数组会导致任何问题...
如有任何建议,我们将不胜感激!
更新 我刚刚意识到花费大部分时间的是:
[searchResultsArray removeObjectsInArray:discardedItems];
最佳答案
尝试快速枚举方式,我的代码片段:
- (void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
self.isFiltered = NO;
}
else
{
self.isFiltered = YES;
self.searchArray = [NSMutableArray arrayWithCapacity:self.places.count];
for (PTGPlace* place in self.places)
{
NSRange nameRange = [place.name rangeOfString:text options:NSCaseInsensitiveSearch];
if(nameRange.location != NSNotFound)
{
[self.searchArray addObject:place];
}
}
}
[self.tableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(self.isFiltered)
return self.searchArray.count;
else
return self.places.count;
}
在 cellForRowAtIndexPath 中:
PTGPlace *place = nil;
if(self.isFiltered)
place = [self.searchArray objectAtIndex:indexPath.row];
else
place = [self.places objectAtIndex:indexPath.row];
// Configure the cell...
cell.textLabel.text = place.name;
cell.detailTextLabel.text = [place subtitle];
关于iphone - 在大数组中搜索字符串需要很长时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12230997/