2

我有一个带有 searchView 和 tableView 的视图控制器,我希望 tableView 根据 searchView 的文本显示来自网络搜索的结果(随着您向搜索添加更多字母而改变)。

正如我现在所拥有的那样,每次添加一个字母时,它都会正确搜索,但应用程序会在搜索时停止,因此在返回最后一个结果之前您无法添加新字母。

有没有更聪明的方法来做到这一点,以便在添加新字母时最后一次搜索基本上中止?

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if(searchText.length>3)
    {
        [self getWebDataWithQuery:searchBar.text]
        [tblResults reloadData];
    }
}
4

4 回答 4

1

您的呼叫[self getWebDataWithQuery:searchBar.text]是呼叫[NSData datawithContentsOfURL:]。那是一个同步调用。您需要使用异步机制从 Web 服务收集数据。使用第三方网络框架,例如 AFNetworking 或 NSULRConnection。

这将允许用户继续输入并且不会阻塞 UI。

于 2013-05-31T17:18:20.103 回答
1

您可以在搜索结果中使用这样的调用

   dispatch_async(dispatch_get_main_queue(), ^{
       [self getWebDataWithQuery:searchBar.text]
       [tblResults reloadData]
    });
于 2013-05-31T17:22:01.573 回答
0

另一种方法(我在我的一个项目中这样做)我为搜索创建了一个 NSOperations。每次更改搜索字符串中的字符时,我都会检查最后一个搜索查询是否与当前查询不相等,如果不是,则取消所有正在执行的操作,然后创建一个新操作并启动它。

当然,所有请求/数据处理都是在后台线程中执行的,只有在下载/解析/处理完成时才会通知 UI。

于 2013-05-31T19:47:33.183 回答
0

你可以做类似的事情:

  • 在视图控制器加载时,您从 web/database/core 数据加载数据
  • 将数据放入数组中(数据可以是对象或字典),在我的示例中是“arrayOfActivities”
  • 创建一个辅助数组,我们称之为“filteredArray”并复制其中的所有内容

然后,在每个数字处,使用谓词更新过滤后的数组。如果您有一个小数据集,这很好(例如,您甚至可以将数据拆分为两个数组并只允许在一个小子集上进行搜索,例如最新的)

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
{
    if (![searchText isEqualToString:@""]) // here you check that the search is not null, if you want add another check to avoid searches when the characters are less than 3
    {
        // create a predicate. In my case, attivita is a property of the object stored inside the array
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(attivita CONTAINS[cd] %@)", searchText];
        self.filteredArray = [[self.arrayOfActivities filteredArrayUsingPredicate:predicate] mutableCopy];
    } else {
        self.filteredArray = [self.arrayOfActivities mutableCopy];  // I used a mutable copy in this example code
    }

    // reload section with fade animation
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
}
于 2013-05-31T17:22:36.073 回答