Call UIView calls related to handler completion?

I call the following class method from my initController method:

[NSURLConnection sendAsynchronousRequest:urlrequest queue:opQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError*error){ // Update an NSMutableArray (an Instance variable [self tableView] reloadData]; // is this ok to call? }]; 

This code works as intended, and the tableView is updated accordingly. My concern: is this threading safe ?. Is it okay to access the user interface element from the completion block?

Thanks,

Winod

+4
source share
2 answers

This is actually not true if opQueue is not + [NSOperationQueue mainQueue]

This completion block will be scheduled in the queue that you provide. In your case, you call this queue "opQueue". If this queue is dropped by some thread other than the main thread, then you should not make this call to reload the table.

Instead, you should do any processing and then insert another block into the main queue, which causes a reboot.

 ^(NSURLResponse *response, NSData *data, NSError*error){ // Do some processing work in your completion block dispatch_async(dispatch_get_main_queue(), ^{ // Back on the main thread, ask the tableview to reload itself. [someTableView reloadData]; }); } 

Or, if processing is easy and fast (and a fixed amount of time), then simply pass mainQueue as "opQueue";

Hope this makes sense. A lot of useful information can be found here: Concurrency Programming Guide

+8
source

This is thread safety. Very important because you do not use threads. The completion handler is simply called later, and not in a separate thread.

+1
source

Source: https://habr.com/ru/post/1385585/


All Articles