Does it necessary to go back to main thread to update UI?

133 Views Asked by At

I was using AFNetworking to deal with the http request.And here is my code:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:URL_LOGIN parameters:parames success:^(AFHTTPRequestOperation *operation, id responseObject) {

    [self.tableview reloadData];

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Request failed");
}];

or:

  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:URL_LOGIN parameters:parames success:^(AFHTTPRequestOperation *operation, id responseObject) {

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableview reloadData];

    });

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Request failed");
}];

Which one is right,does it necessary to use dispathc_get_main_queue(),or the AFNetworking fix everything? Anybody knows?Thanks in advance.

2

There are 2 best solutions below

1
On BEST ANSWER

On one hand, AppKit and UIKit is not thread safe, so you have to do any UI-related work on the main thread.

But as for AFNetworking, it automatically makes sure that the callbacks (success or failure) is executed on the main thread (unless you set otherwise). So normally you do not have to explicitly use dispatch_get_main_queue to dispatch your work to the main thread.

To check whether the callback is on the main queue:

[manager POST:someURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    if (operation.completionQueue == NULL) {
        // is main queue
    }
}...

Documentation

0
On

UI update always happens in main thread.So your tableview needs to be reloaded in main thread. So the second one is true.