iphone - 在大数组中搜索字符串需要很长时间

标签 iphone objective-c ios nsstring searchbar

我正在实现一个搜索字段,它根据用户输入的文本过滤 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/

相关文章:

javascript - javascript geolocation 是否应该提示用户打开定位服务?

jquery - 为什么 jQuery Mobile 固定工具栏在 Mobile Safari 中没有固定?

ios - 从文档目录获取文件路径 - Objective-c iOS

objective-c - 使用 Objective C 解码 XML 实体

iphone - UITableView deleteRowsAtIndexPaths 不删除行

ios - xcode 核心数据类中的数据类型不匹配

iphone - 为什么我在 ARC 下比较桥接 CGColorRefs 时遇到崩溃?

ios - 在不显示打印界面的情况下,在 Swift 中从 HTML 生成带有图像的 PDF

ios - Xcode - 如何修复 'NSUnknownKeyException' ,原因 : … this class is not key value coding-compliant for the key X"error?

iphone - 动画和调整 UIImageView