JoseSwagKid
JoseSwagKid

Reputation: 389

Why is dispatch_async bad? What is a nicer way of accomplishing the same task?

     dispatch_async(dispatch_get_main_queue(), ^{
         [self.teamName becomeFirstResponder];
     });

I was chatting with a friend, and he told me that he had heard using dispatch_async is not very good, but he was not sure why.

I checked on Google and did not find any reason why this code is wrong

How can I improve on this code? Is there a nicer way to do this?

Note: I am still learning iOS programming, so I am new to this whole thing.

Upvotes: 2

Views: 1135

Answers (2)

Mark Bernstein
Mark Bernstein

Reputation: 2080

Your friend is mistaken in thinking that dispatch_async is "bad".

But there's no point in asking another processor to do something as easy as becomeFirstResponder! It takes some time to set up the dispatch, and it takes almost no time to become first responder. Worse, if side effects of being the first responder might involve things, such as drawing, that need to be done on the main thread.

Use dispatch_async to shuttle off processor or network-intensive tasks to other threads. Read up on Grand Central Dispatch specifically, and on concurrent programming generally. It's powerful, but like all powerful programming constructs it can cause trouble if you don't understand what you're doing.

What your friend might have been thinking about is simply that iPhones and iPads don't have as many processing cores as does a typical Macintosh, and some have only one core. On these, you won't get the benefits of employing multiple processors at one time. But there are still good reasons to do things like fetching web pages asynchronously, so they don't interrupt things like scrolling or navigation animations.

Upvotes: 5

Khaled Barazi
Khaled Barazi

Reputation: 8741

I am not sure what your friend is referring to but

dispatch_async(dispatch_get_main_queue(), ^{
     [self.teamName becomeFirstResponder];
 });

dispatch_async is very robust. Being new to it, you will mainly use it to run some code intensive in a different queue than the UI so that the UI remains responsive and once you have a value (or image or anything UI related that you need to update), you will end up calling the main queue as above.

Stick to the facts..Don;t worry about your friend.

Upvotes: 3

Related Questions