KVO rocks. Now how do I use it asynchronously?

北慕城南 提交于 2019-12-21 05:22:26

问题


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.


回答1:


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.




回答2:


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).




回答3:


Use the Receptionist Pattern as recommended by Apple https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/ReceptionistPattern/ReceptionistPattern.html



来源:https://stackoverflow.com/questions/1282709/kvo-rocks-now-how-do-i-use-it-asynchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!