如何调用方法a.s.a.p.但最早在下一次运行循环迭代中? [英] How to call a method a.s.a.p. but at earliest in the next run loop iteration?
问题描述
我需要一种保存方式来说:iOS,我希望这个方法尽快执行,但不要在这个循环迭代中执行。最早在下一个,但请不要在这一个。谢谢。
I need a save way to say: "iOS, I want this method to be executed a.s.a.p., but NOT in THIS run loop iteration. At the earliest in the next, but please not in this one. Thank you."
现在我总是这样做:
[self performSelector:@selector(doSomethingInNextRunLoop) withObject:nil afterDelay:0];
[self doSomeOtherThings];
假设 -doSomeOtherThings
将永远在
之前执行 -doSomethingInNextRunLoop
。
文档说:
指定延迟0并不一定会导致选择器立即执行
。选择器仍在线程的
运行循环中排队,并尽快执行。
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.
所以基本上它可能发生在该方法被立即调用,就像我刚刚发送了一条直接消息一样,导致 -doSomethingInNextRunLoop
在 -doSomeOtherThings
之前执行?
So basically it can happen that the method gets called immediately as if I had just sent a direct message, causing -doSomethingInNextRunLoop
to be executed before -doSomeOtherThings
?
我怎样才能确保它会被asap调用但是从来没有在同一个运行循环迭代中?
How can I make absolutely sure it will be called a.s.a.p. but NEVER ever in this same run loop iteration?
澄清措辞:运行循环我指的是主线程,以及所有方法必须返回的迭代,直到线程已经为新事件再次准备好了。
To clarify the wording: With run loop I mean the main thread, and the iteration in which all methods must return until the thread is ready again for new events.
推荐答案
如果你担心苹果可能有一天特殊情况延迟0,你总是可以指定1e-37左右的延迟。虽然 performSelector:withObject:afterDelay:
可以很容易地被读取以保证选择器将始终被安排用于下一个运行循环迭代。
If you're worried that Apple may someday special-case a delay of 0, you could always specify a delay of 1e-37 or so. Although the documentation for performSelector:withObject:afterDelay:
could easily be read to guarantee that the selector will always be scheduled for the next run loop iteration.
如果你担心Apple有一天特殊情况下的延迟会低于某个任意下限,你总是可以尝试使用NSRunLoop的 performSelector:target:argument:order:modes:
文档明确指出将为下一次运行循环迭代计划执行。
If you're worried that Apple may someday special-case delays less than some arbitrary lower bound, you could always try using NSRunLoop's performSelector:target:argument:order:modes:
which the documentation specifically states will schedule execution for the next iteration of the run loop.
这篇关于如何调用方法a.s.a.p.但最早在下一次运行循环迭代中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!