Tapas Pal
Tapas Pal

Reputation: 7207

Understanding the below code

I just tried the below code

dispatch_async(dispatch_get_main_queue(), ^{
        [self taskB];
    });

[self performSelectorOnMainThread:@selector(taskA) withObject:nil waitUntilDone:NO];

This taskA and taskB executing a NSLog and nothing else. Now here as taskB written first but taskA executing first. Even I change the order still performSelectorOnMainThread executing first. And for each case my console shows

2015-03-17 16:44:35.157 TestProject[9346:191978] Task A
2015-03-17 16:44:35.283 TestProject[9346:191978] Task B

Can anybody help me to understand what is happening here. And why performSelectorOnMainThread execute first?

Upvotes: 0

Views: 52

Answers (3)

Sanjay Mohnani
Sanjay Mohnani

Reputation: 5967

Please visit this page, addresses the same topic

https://blackpixel.com/writing/2013/11/performselectoronmainthread-vs-dispatch-async.html

Upvotes: 0

Mohd Prophet
Mohd Prophet

Reputation: 1521

dispatch_async(dispatch_get_main_queue(), ^{
        [self taskB];
    });

In this code you are using dispatch_async that tells the compiler not to halt the further execution for the code written within it,So the compiler continues to execute the performSelectorOnMainThread and after that the compiler thinks about the dispatch. Read More about Dispatch(GCD) here.

Upvotes: 3

erenkabakci
erenkabakci

Reputation: 442

You are initiating an asynchronous task with dispatch_async which does not guarantee that it will be executed immediately.

But on the other hand you are telling your main queue (which is generally default queue on your lifecycle) that you want to execute task A.

So whenever the code runs the block is going to be skipped asynchronously and continue performing task A. After that task ends task B is going to be initiated asynchronously.

Upvotes: 2

Related Questions