I’ll start by saying that I’m new to cocoa development. I’m also surprised I didn’t find a post about this already, but I’ve filtered through a number of posts now without success.
I have a set of elements that should change state based on the state of a long running algorithm.
Basically, I have a start button, a cancel button, and a next button. The initial state of the app would be start button enabled, cancel and next buttons disabled. The status of the algorithm should swap enabled / disabled on all the buttons as it progresses.
Every option for manipulating button state I have seen involves coding button.enabled into the controller code. I’m coming from an ASP .NET MVC background as I dive into Cocoa and this seems backwards to me. Shouldn’t the view logic be separated from the controller logic in the MVC pattern?
To me, it seems I should be able to emit a couple boolean values as IBOutlets like algorithm running and algorithm success, and bind the button state at the view layer. Do I need to toss this idea? Or am I possibly missing something about the Cocoa version of design pattern (like the object I bind the view to should really be a view model, which interacts with a controller class)? Or, lastly, is there an easy way to accomplish what I’m talking about, and I’ve just missed it.
You don’t need to code the enabled state of the button into your controller. What you can do is declare a
BOOLproperty on your controller such asisBusyand then set this property toYESwhen you start your long operation and toNOwhen it’s finished. You must do this using Key-Value Coding-compliant methods, which essentially means using the setter, so you’d callself.isBusy = YES;, for instance.The reason you do this is because you can then use Cocoa Bindings to set up a binding on the UI controls. Go into the bindings inspector for one of your buttons, and bind the
Enabledbinding to your controller object with a key path ofisBusy.Cocoa bindings uses Key-Value Observing (KVO) to monitor the value of observed properties. When a change occurs in the
isBusyproperty, the buttons that are bound to it will notice and change theirenabledstate in response.