简体   繁体   中英

How to update data on the main thread after running code in the background?

I have this dispatch_queue code that I'm using to make 3 different data requests. Then I'm updating the tableView on the main thread. What else can I put in the main thread? I'm using this [self requestExtendedData]; to download data from a web service that is then parsed and set to UILabels etc...

My question is: if I have the [self requestExtendedData]; running in the background thread how do I update the UILabels with the content from this data in the main thread? Should I put everything else in the main thread area? All the UIView, UILabels and UIButton objects etc...

thanks for the help

dispatch_queue_t jsonParsingQueue = dispatch_queue_create("jsonParsingQueue", NULL);

// execute a task on that queue asynchronously
dispatch_async(jsonParsingQueue, ^{

    [self requestUserData]; // request user comments data
    [self requestExtendedData]; // request extended listing info data
    [self requestPhotoData]; // request photo data


    // once this is done, if you need to you can call
    // some code on a main thread (delegates, notifications, UI updates...)
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];


    });
});

// release the dispatch queue
dispatch_release(jsonParsingQueue);

This is what apple document saying:

Note: For the most part, UIKit classes should be used only from an application's main thread. This is particularly true for classes derived from UIResponder or that involve manipulating your application's user interface in any way.

That means you should put all your UIView , UILabels and UIButton objects code in the main thread like this:

dispatch_async(dispatch_get_main_queue(), ^{
    [self.tableView reloadData];
    // Your UI update code here
});

For Swift3 :

DispatchQueue.main.async{
   self.tableView.reloadData()
   // any UI related code 
   self.label.text = "Title"
   self.collectionView.reloadData()
   }

Try something like this after your dispatch_async

[self performSelectorOnMainThread:@selector(doUIStuffOnMainThread:)
                       withObject:self.tableView.data 
                    waitUntilDone:YES];
[your_tableview performSelectorOnMainThread:@selector(reloadData)
                                     withObject:nil
                                  waitUntilDone:YES];

Try adding one main queue operation like this :

[[NSOperationQueue mainQueue] addOperationWithBlock:^{
    [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