Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 876
user2588945 Avatar asked Oct 22 '22 03:10

user2588945


2 Answers

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
});
like image 117
liuyaodong Avatar answered Nov 01 '22 16:11

liuyaodong


For Swift3 :

DispatchQueue.main.async{
   self.tableView.reloadData()
   // any UI related code 
   self.label.text = "Title"
   self.collectionView.reloadData()
   }
like image 41
Pranav Gupta Avatar answered Nov 01 '22 15:11

Pranav Gupta