【发布时间】:2013-10-05 13:35:38
【问题描述】:
在我的 iOS 应用程序中,我想在更新 UI 之前等待条件变为真。 我是这样做的:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
while (!condition) NSLog("waiting for the condition");
dispatch_sync(dispatch_get_main_queue, ^{
//update the UI here
});
});
上面的代码工作得很好,但是我想问一下使用 while 循环来做等待工作是否好,以及是否有更好的方法。 谢谢!
---更新
条件实际上是 4 个 BOOL 变量的组合。每个变量都与来自服务器的内容请求相关联。我正在使用 AFNetworking 框架。在 4 个请求的每一个的完成块中,我将关联的 BOOL 变量设置为 YES。 所以,实际的while循环是这样的:
while (!([MyRequest request1].isFinished && [MyRequest request2].isFinished && [MyRequest request3].isFinished && [MyRequest request4].isFinished)) NSLog("waiting for the condition");
【问题讨论】:
-
你能给我们一个不那么抽象的例子吗?您要检查的
condition到底是什么?不同的场景建议使用不同的方法(信号量、KVO、重复NSTimer、CADisplayLink等)。但是这种while循环方法通常并不可取。 -
我只是想简化问题,但这让我的问题变得更糟。只需更新详细信息,@Rob。
-
这很有帮助。在这种情况下,我只需创建一个新操作,并使其依赖于其他四个请求操作。请参阅修订后的答案。 (仅供参考,这有效地对这四个操作的
isFinished属性执行 KVO。)
标签: ios asynchronous grand-central-dispatch