Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KVO rocks. Now how do I use it asynchronously?

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.

like image 254
dugla Avatar asked Dec 05 '22 05:12

dugla


1 Answers

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

like image 142
bbum Avatar answered Dec 18 '22 01:12

bbum