How to call a method a.s.a.p. but at earliest in the next run loop iteration?

人走茶凉 提交于 2019-12-03 01:54:39

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.

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.

Quite trivial using GCD (Grand Central Dispatch):

dispatch_async (dispatch_get_main_queue (), ^{
    NSLog (@"This stuff runs in the next iteration of the main run loop");
});

I think you conclusion from reading the documentation is wrong.

So basically it can happen that the method gets called immediately as if I had just sent a direct message

No. The part of the documentation you quote says that the selector is always queued on the run loop, no matter what. So it will never be executed just as a direct message.

The first sentence with the "not necessarily" might be a bit misleading, but I think the second sentence should really clarify that what you fear is not gong to happen.

Surely you just do this;

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

Which guarantees the execution order you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!