Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC and cocoa bindings best practices question

Lets say I have a view, myView, a view controller, myViewController, and some sort of model object, myModel. Further, lets say the model has two KVO compliant properties, arrayOfPeopleNames and arrayOfAnimalKinds (both NSStrings).

In my view I want to have two pop-ups bound to the contents of these two arrays.

My question is, if myController has a reference to myModel, and the dropdown is bound to myViewController is it good practice to set a keypath along the lines of myModel.arrayOfPeopleNames?

Or do I need to set up an additional NSArray in myViewController which mirrors the one in myModel and bind to that keypath instead?

The former seems a lot simpler from an implementation point of view (I don't have to make the controller array mirror the model array), but I'm wondering about whether it exposes the model to much to the view.

Opinions?

like image 845
Lawrence Johnston Avatar asked Dec 10 '08 17:12

Lawrence Johnston


1 Answers

You shouldn't mirror the model's array in the controller. Although I wouldn't be too concerned about binding directly to the model's array in a very simple case, you could also bind your UI objects to an NSArrayController, which manages the model's array. This would provide separation between the model and UI, and more importantly handle tasks like sorting, selection, adding and removing objects, and so on.

I can see where you're coming from by being concerned KVO and bindings violates "pure" model view controller design, but it's not something you should worry about. Even though the KVO notifications pass directly to the view from the model, setting up and changing the connection between the view and model is still the responsibility of the controller (only in this case it's done through IB instead). For instance, you wouldn't want a model object to get a reference to the view, and bind itself to the UI, that would be the controller's responsibility.

As another example of something to avoid, consider if instead your model had an array of "animal IDs" instead of names. Instead of creating a method to translate animal IDs to human readable animal names in the model, you might instead want to create a value transformer or formatter to do the conversion. This allows you to maintain that level of separation between the model and view.

Keep in mind also that the purpose of design patterns is to reduce the complexity of coding a solution to a problem, never to increase it. You'll see that this is exactly the way Cocoa works, even though it might not always adhere to the strictest definition of a pattern.

like image 142
Marc Charbonneau Avatar answered Oct 18 '22 18:10

Marc Charbonneau