Sleep 和 NSRunLoop runMode:beforeDate 之间的区别:

发布于 2024-12-10 13:35:58 字数 294 浏览 4 评论 0原文

我最近发现,当等待 NSURLConnections 通过时,如果我告诉等待线程执行以下操作,效果会更好:

[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distanceFuture]];

而不是

[NSThread sleepForTimeInterval:1];

在阅读了一些关于 NSRunLoop runMode:beforeDate: 的内容之后,听起来它总是比睡眠更好。人们发现这是真的吗?

I have recently found that when waiting for my NSURLConnections to come through it works much better if I tell the waiting thread to do:

[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];

instead of

[NSThread sleepForTimeInterval:1];

After reading a bit about NSRunLoop runMode:beforeDate: it sounds like it is preferable over sleep just about always. Have people found this to be true?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忆伤 2024-12-17 13:35:58

是的,NSRunLoop 更好,因为它允许 runloop 在您等待时响应事件。如果您只是休眠线程,即使事件到达(例如您正在等待的网络响应),您的应用程序也会阻塞。

我通常有这样的结构:

while ([self isFinished] == NO) {
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}

然后当你想停止阻塞时让 isFinished 返回 true 。艾斯

Yes, NSRunLoop is better because it allows the runloop to respond to events while you wait. If you just sleep your thread your app will block even if events arrive (like the network responses you are waiting for).

I usually have this construction:

while ([self isFinished] == NO) {
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}

And then have isFinished return true when you want to stop blocking. Eith

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文