简体   繁体   中英

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.

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];
});

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM