KVO 很震撼。 现在我该如何异步使用它?

发布于 2024-08-02 04:13:37 字数 210 浏览 9 评论 0原文

我对 KVO 很感兴趣,但如果以明显的方式使用它是同步的。 我想在以下情况下使用它:我快速连续地发出许多 KVO 消息,并且它导致我的应用程序在处理 KVO 消息时逐渐停止。 有人可以建议一种方法 - 也许使用 NSOperationNSThread - 在这里可行吗?

我的目标是尽可能保留 KVO 的解耦性和灵活性。

I am sold on KVO but if used in the obvious way it is synchronous. I would like to use it in a situation where I am firing off many KVO messages in rapid succession and it is causing my app to grind to a halt as the KVO messages are handled. Can someone suggest an approach - perhaps using NSOperation or NSThread - that will work here?

My goal is to retain the decoupled, flexibility of KVO if possible.

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

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

发布评论

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

评论(3

涫野音 2024-08-09 04:13:37

KVO 本质上是单线程的,因为 KVO 通知将在与更改相同的线程上传递。

当然,UIKit 和 Cocoa 都只希望您在主线程上欺骗 UI 元素。

因此,如果您正在进行异步操作,那么您很可能正在使用线程,如果是这样,则已经存在同步问题,因为您需要将通知从某个线程获取到主线程。

关键就在于此。 您可以在将更改通知传递到主线程之前合并这些更改通知,而不是盲目地转发每个更改通知。

您可以通过多种方式来执行此操作。 特定的解决方案很可能对于您的应用程序来说是非常独特的。

就我个人而言,我尽量避免细粒度操作的合并和转发。 我发现告诉主线程对象的特定子图已更改要简单得多。 更有可能的是,使更改对用户可见的绘制代码将需要重绘相关状态,因此,相关更改将自动反映。

正如您所猜测的,关键是限制通知,这样您就不会降低应用程序的响应速度(或破坏设备的电池寿命)。

KVO is inherently single threaded in that the KVO notifications will be delivered on the same thread as the change.

Of course, UIKit and Cocoa both really only want you to be diddling UI elements on the main thread.

Thus, if you are doing asynchronous operations, you are most likely using threads and, if so, already have a synchronization issue in that you need to get the notifs from some thread to the main thread.

And therein lies the key. Instead of blindly forwarding each change notification as it comes in, you can coalesce the change notifications before passing them on to the main thread.

There are a variety of means via which you can do this. The specific solution is going to be quite unique to your application, most likely.

Personally, I try to avoid coalesce-and-forward of fine grained operations. I find it far simpler to tell the main thread that a particular sub-graph of objects have changed. More likely than not, the drawing code that will then make the changes visible to the user is going to need to redraw related state and, thus, related changes will be automatically reflected.

The key, as you have surmised, is to throttle the notifications so you don't bog down app responsiveness (or destroy the devices battery life).

旧伤还要旧人安 2024-08-09 04:13:37

查看 NSNotification。这并不完全相同,但您可以在后台线程上发出通知(需要进行一些研究和工作)。您可以保持良好的解耦和即发即弃行为。

Check out NSNotification. It's not quite the same thing, but you can fire off notifications on background threads (with a little bit of research and work). You can maintain the nice decoupling and fire-and-forget behavior.

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