调度无法正常运作

时间:2015-04-21 13:59:29

标签: ios objective-c uitableview grand-central-dispatch searchbar

我尝试在后台获取一些数据并在搜索栏中输入时刷新tableview,有我当前的代码:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        Games * game = [[Games alloc] init];
        NSArray * temp = [game comingSoonWithPlatform:@"pc" header:[game gameHeader] parseLink:[game gameComingSoonListLinkWithPlatform:@"pc"]];
        self.searchArray = [temp valueForKey:@"results"];
        [self.tableView reloadData];
    });
}

我做错了什么?如果我在搜索栏中再输入一个单词,或者点击取消按钮,则会刷新,数据会显示在tableview中。

2 个答案:

答案 0 :(得分:2)

[self.tableView reloadData];的调用必须在主线程上。替换

[self.tableView reloadData];

dispatch_async(dispatch_get_main_queue(), ^{
    [self.tableView reloadData];
});

答案 1 :(得分:2)

从主线程创建后台线程,在进行任何处理后,您需要切换到主线程来更新UI。

例如,您可以使用以下方法编写代码 -

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    // [activityIndicator startAnimating];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // do your background code here
        Games * game = [[Games alloc] init];
        NSArray * temp = [game comingSoonWithPlatform:@"pc" header:[game gameHeader] parseLink:[game gameComingSoonListLinkWithPlatform:@"pc"]];
        self.searchArray = [temp valueForKey:@"results"];

        dispatch_sync(dispatch_get_main_queue(), ^{
            // you are now on the main queue again, update ui here  
        //[activityIndicator stopAnimating];
        [self.tableView reloadData];
        });
    });
}