1

Here is the code that using block to call:

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

And this one is calling using selector:

[self performSelectorOnMainThread:@selector(doSomething)
 withObject:nil
waitUtilDone:NO];
DNB5brims
  • 29,344
  • 50
  • 131
  • 195

1 Answers1

2

Yes — in the first case you create a block and post that off to the main queue. dispatch_async will copy the block. Copying a block causes it to retain every object it references. So self will be retained, as would any other object you mention in the block. The mechanism that keeps hold of the block is Grand Central Dispatch.

In the second case you simply schedule a call to doSomething on the main thread. The mechanism that makes the call will be a run loop. self and at most one argument object will be retained.

A difference between GCD and run loops is that run loops have modes. You queue things up to be executed only when the run loop is in a compatible mode. In practice you'll most commonly use that by queueing something up to occur in NSDefaultRunLoopMode. When the user is interacting with the user interface it switches into a mode other than the default. Therefore your work will not occur until the user stops interacting. E.g. on iOS the user is considered to be interacting while their finger is down. So you can arrange for work that you know is too heavy to allow, say, smooth scrolling to continue so that it doesn't happen until immediately after the user has finished the interaction.

The selector you nominate will use NSRunLoopCommonModes which includes tracking (user interaction) mode but compare and contrast with performSelectorOnMainThread:...modes:.

Tommy
  • 99,986
  • 12
  • 185
  • 204
  • Are you certain? I'm pretty sure `performSelectorInMainThread:…` does retain the receiver as well as the argument. – Chuck Oct 01 '13 at 01:49
  • @Chuck I couldn't find a definitive answer in the documentation but simple testing suggests you're right, so it's a pretty safe guess the call goes through `NSRunLoop` `- performSelector:target:argument:order:modes:` – Tommy Oct 01 '13 at 03:17