Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between "performSelector:withObject:afterDelay:" where delay is 0, and just calling the selector?

I'm working on an iPad project that uses a third-party SDK, and have been reading through the SDK code to learn about it and objective-c. I came across the following line in an asynchronous callback:

[self performSelector:@selector(doSomething) withObject:nil afterDelay:0];

I've read through the documentation on that selector. The relevant line appears to be the following:

Specifying a delay of 0 does not necessarily cause the selector to be performed immediately. The selector is still queued on the thread’s run loop and performed as soon as possible.

I can't determine why one should write [self performSelector:@selector(doSomething) withObject:nil afterDelay:0], as opposed to merely writing [self doSomething]. It seems to me that a delay of zero means that the call should be made immediately. Clearly I'm missing something, it's unlikely that the framework author chose this approach at random. Other StackOverflow answers don't shed any light on this either. Is the "performSelector" selector being used because the doSomething selector itself is asynchronous, and the call is being made in an asynchronous callback?

I did find another link suggesting the following:

It's interesting to note that using performSelector with afterDelay will also let the warning [viz, a compiler warning] go away: ...

[self performSelector:aSelector withObject:nil afterDelay:0.0];

So did the author use this code to suppress a compiler warning only? If that's the case, then it's probably preferable to suppress the warnings through clang push/pops, as suggested in this thread.

If anyone has a cogent explanation as to why the author used the ...afterDelay method, I'd be grateful. Thanks.

Edit Oct 22, 2012: I don't believe that the sole answer given here by @rmaddy is wholly applicable to my situation, but it's still a good answer, so I'll accept it. I'll keep tabs on this question and come back if I find anything new. Thanks. J.Z.

like image 395
J.Z. Avatar asked Oct 19 '12 03:10

J.Z.


1 Answers

One possible use of something like:

[self performSelector:@selector(doSomething) withObject:nil afterDelay:0];

is to allow the current runloop to complete before 'doSomething' is called. In other words, the current call stack can be completed (the current method returns) before 'doSomething' is called. Often this is used to give the UI a chance to update.

It's hard to know the author's true intent though without more context but this is a common use.

like image 119
rmaddy Avatar answered Oct 14 '22 06:10

rmaddy