Using [[NSRunLoop currentRunLoop] runUntilDate:[NS

2019-08-05 06:58发布

问题:

In my application at some point I have a bunch of messages scheduled using performSelector.

Under some conditions, while handling an UI action, I need to wait for all the currently scheduled selectors to fire.

I could place my code in another method and schedule it using performSelector:target:argument:order:modes: with order value high enough to be sure it will fire last, but there are reasons why I think that would make an ugly solution.

So I send [[NSRunLoop currentRunLoop] runUntilDate:[NSDate date]] and it seems to work just like I need it to.

Still, I'm not sure if that is a legitimate way to let the run loop roll for just one iteration. Also, are there any potential troubles associated with this approach?

回答1:

Okay, answering my own question.

First of all it's a duplicate (also, this).

Next, generally, sending [[NSRunLoop currentRunLoop] runUntilDate:[NSDate date]] from within the same run loop is a bad idea:

  1. In theory, autorelease pool will get drained that way. In practice, I've not been able to make my app crash by using objects allocated pre-runUntilDate (under ARC), but better not to risk anyway.

  2. If somehow another action gets dequeued during that runUntilDate it might cause some unexpected side effects.

TL;DR I should do myself a favor and replace that piece of code with something more deterministic.