【问题标题】:SearchBar hangs on iphone but works fine on simulatorSearchBar 在 iphone 上挂起,但在模拟器上运行良好
【发布时间】:2013-04-30 21:13:59
【问题描述】:

我的应用程序有大约 200 个 UITableView 行,当我在 xcode 上使用模拟器通过 UISearchBar 过滤数据时,它会立即过滤并显示结果但是,当我在我的 iphone(iphone4、iOS 5.1.1)中运行我的应用程序时,它挂起在显示任何搜索结果之前等待几秒钟。我正在使用此代码过滤数据...

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
[self.filteredData removeAllObjects];

if ([searchText length] > 0) {
    self.isSearching = YES;
    for (AClass *filteredData in self.allData) {
        NSRange titleResultRange = [filteredData.name rangeOfString:self.searchBar.text options:NSCaseInsensitiveSearch];
        if (titleResultRange.location != NSNotFound) {
            [self.filteredData addObject:filteredData];
        }
    }
}
else self.isSearching = NO;
[self.tableView reloadData];}

我相信我的代码没问题,因为它在模拟器上运行得非常好,我需要做些什么来让它在 iphone 上运行得更快吗? 顺便说一句,我的 iPhone 运行良好,我使用其他应用程序,它们对我来说运行良好..

【问题讨论】:

    标签: iphone ios uisearchbar


    【解决方案1】:

    您的设备花费的时间比模拟器长的原因是可用内存量。作为一般规则,不要使用您的应用在模拟器中的性能来判断您的应用的性能。

    如果您以您描述的方式过滤一个非常大的数据集,我建议您使用调度队列来执行您的搜索,而不是在主队列中执行所有操作。你可以在这里阅读它们:http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html

    如果您不想阅读整个文档,这里有一个示例,说明您的代码会是什么样子。

    - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
        [self.filteredData removeAllObjects];
    
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            if ([searchText length] > 0) {
                self.isSearching = YES;
                for (AClass *filteredData in self.allData) {
                    NSRange titleResultRange = [filteredData.name rangeOfString:self.searchBar.text options:NSCaseInsensitiveSearch];
                    if (titleResultRange.location != NSNotFound) {
                        [self.filteredData addObject:filteredData];
                    }
                }
            }
            else self.isSearching = NO;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        });
    }
    

    请注意,我给您的示例不是线程安全的...您需要确保在任何给定时间只执行一次搜索,否则此代码将崩溃,因为将引用相同的数组多个队列。如果您需要更多帮助,请发表评论,我会尽力解决。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-08
      • 1970-01-01
      相关资源
      最近更新 更多