Search code examples
cocoaconcurrencykey-value-observingnsoperation

How do I bind a NSProgressIndicator to a property of a NSOperation?


I've got a window which reflects the status of an NSOperation. How should I bind the NSProgressIndicator to the NSOperation's progress-property?


Solution

  • AppKit is not thread-safe. Any updates to a UI object must happen on the main thread. KVO doesn't dispatch observation messages across threads. So you'll need and another way of updating the progress indicator than just plain KVO.

    In your NSOperation's main method, you'll need to dispatch progress messages periodically. The easiest thing to do would be to use NSNotificationCenter with a custom notification so that the main thread can listen for the updates. (Note that notifications are always delivered on the thread from which they were sent, so you'll need to use the performSelectorOnMainThread: method to make sure the notifications are delivered on the UI thread.)

    In your main thread, you'll need to add your class as an observer to receive those notifications and update the progress indicator. If you want to use bindings for the progress indicator, you can bind it to a property on your controller object that you update when you receive progress notifications from the NSOperation.