25

What's the difference between this:

[[NSOperationQueue mainQueue] addOperationWithBlock:^{
    [self doSomthing:object];
}];

and this:

[self performSelectorOnMainThread:@selector(doSomething:) withObject:object waitUntilDone:NO]
Mike Z
  • 4,121
  • 2
  • 31
  • 53
ma11hew28
  • 121,420
  • 116
  • 450
  • 651

1 Answers1

36
[self performSelectorOnMainThread:@selector(doSomething:) 
                       withObject:object 
                    waitUntilDone:NO]

Will perform the selector right when it is called. This is what you have to use if you want to affect the UI from a background thread. If you say YES to waitUntilDone it will block the thread until the method has completed.

mainQueue adds that block to the operation queue of the mainthread but does not guarantee when it will be executed. There could be other items in that queue still waiting to execute.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Mike Z
  • 4,121
  • 2
  • 31
  • 53
  • Very clear explanation; I wonder why the OP hasn't accepted it as the answer. Could you provide a link to the official docs on both techniques? – JohnK May 18 '13 at 17:12
  • 1
    Don't think that this method is synchronous, the answer seems wrong to me. – Blitz Jun 23 '14 at 00:13
  • 4
    My understanding of the `performSelectorOnMainThread` with waitUntilDone:NO is that it is executed on the next go around of the run loop, which is the exact same behavior as the mainQueue – Blitz Jun 23 '14 at 07:09