I saw a lot of topics about it and still unclear ..
1)
When I doing :
dispatch_async(dispatch_get_main_queue(), ^(void) {
for(int i = 0; i < 10000000; i++)
{
NSLog(@" i = %i", i);
}
});
The UI is froze, I can't click in any button. If I understand, it's because it's called on dispatch_get_main_queue, that's say the main thread ? So why talking about "background" if the UI is froze ?
2)
dispatch_async(dispatch_get_main_queue(), {
self.tableData = results
self.appsTableView!.reloadData()
})
})
The context : I get back some data (session.dataTaskWithURL ) from an api service and when I received all informations, I'm doing this dispatch.
But I didn't understood the explanations, I quote :
"Because this task happens in the background, we need to jump in to the foreground before we update the UI. So we need to use dispatch_async to move back in to the main thread, and reload the table view."
Hum ?? It is because the session url was in background and now it's necessary to come back to the main thread ? And what if we don't come back ?
3) I listened something like updating the UI from another thread is not safe. Why ?
4) A little HS, but will be nice : Now, I'm waiting that the request finish to receive all informations and display it to the UI. It can be 3 secondes for exemple. During this laps of tame, the UI is empty. It is possible to display informations in the UI little by little the data are received and not waiting that the request finish ?
Thanks a lot in advance, all !
1) You're dispatching to the main thread so it is going to be a blocking operation. Instead, you want to dispatch to a different thread.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
// this is on a background thread
for (int i = 0; i < 10000000; i++) {
NSLog(@"i = %i", i);
}
dispatch_async(dispatch_get_main_queue(), ^(void) {
NSLog(@"Done - this is on the main thread.");
});
});
2) The previous dispatch block that you were in was in the background, so now you dispatch to the main thread within that block to perform UI tasks (all UI tasks MUST be performed on the main thread).
3) From the documentation:
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.
4) As some background tasks finish, you can call to the main thread to update UI for sure. ex:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
for (int i = 0; i < 10000000; i++) {
NSLog(@"i = %i", i);
if (i % 1000000 == 0) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
NSLog(@"Another million is done (this is on the main thread)");
});
}
}
dispatch_async(dispatch_get_main_queue(), ^(void) {
NSLog(@"Done - this is on the main thread.");
});
});