当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - Dispatch doesn't work properly

问题描述:

I try to get some data in background and refresh a tableview when typing in the search bar, there is my current code:

- (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];

});

}

What am I doing wrong? If I type one more word in the search bar or if I tap the cancel button, it is refreshing and the data appear in tableview.

网友答案:

From main thread you are creating background thread, and after doing any processing there you need to switch to main thread to update UI.

For example, you can do your coding stuff in below method as-

- (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];
        });
    });
}
网友答案:

The call to [self.tableView reloadData]; has to be on the main thread. Replace the line

[self.tableView reloadData];

with

dispatch_async(dispatch_get_main_queue(), ^{
    [self.tableView reloadData];
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: