KVO 很震撼。 现在我该如何异步使用它?
我对 KVO 很感兴趣,但如果以明显的方式使用它是同步的。 我想在以下情况下使用它:我快速连续地发出许多 KVO 消息,并且它导致我的应用程序在处理 KVO 消息时逐渐停止。 有人可以建议一种方法 - 也许使用 NSOperation
或 NSThread
- 在这里可行吗?
我的目标是尽可能保留 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
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).
按照 Apple https:/ 的建议使用接待员模式/developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/ReceptionistPattern/ReceptionistPattern.html
Use the Receptionist Pattern as recommended by Apple https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/ReceptionistPattern/ReceptionistPattern.html
查看 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.