7

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.

4

1 回答 1

6

一种可能的用途,例如:

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

是允许当前运行循环在调用 'doSomething' 之前完成。换句话说,当前调用堆栈可以在调用 'doSomething' 之前完成(当前方法返回)。通常这用于给 UI 一个更新的机会。

尽管没有更多上下文,但很难知道作者的真实意图,但这是一种常见的用法。

于 2012-10-19T03:43:29.270 回答