MVC Delegation – Understanding MVC and Delegation

delegatesmvc

I am a beginning iOS programmer and use the Model-View-Controller model as a design pattern: my model doesn't know anything about my view (in order to make it compatible with any view), my view doesn't know anything about my model so they interact via my controller. A very usual way for a view to interact with the controller is through delegation: when the user interacts with the app, my view will notify my controller, which can call some methods of my model and update my view, if necessary.

However, would it make sense to also make my controller the delegate of my model? I'm not convinced this is the way to go. It could be handy for my model to notify my controller of some process being finished, for example, or to ask for extra input of the user if it doesn't have enough information to complete the task. The downside of this, though, is that my controller would be the delegate for both my controller and my model, so there wouldn't be really a proper way to notify my model of changes in my view, and vice versa. (correct me if I'm wrong.)

Conclusion: I don't really think it's a good idea to to have my controller to be the delegate of my model, but just being the delegate of my view would be fine. Is this the way most MVC models handle? Or is there a way to have the controller be the delegate of both the controller and the model, with proper communication between them?

Like I said, I'm a beginner, so I want to do such stuff the right way immediately, rather than spending loads of hours on models that won't work anyway. 🙂

Best Answer

I'll speak specifically to iOS as it has its own concepts and some language features make its way of doing things a good fit. Often in iOS the Controller - Model layer interactions are based on some variant of Observer pattern (key-value observing (KVO) but also NSNotification). I find the model layer often doesn't engage in the same type of interactive back and forth that happens in the View - Controller layer interface (think the complexity of a dynamic, fully-featured table view), so delegation is not the most natural fit. Usually something (user input, a network request, etc) changes the model, and the controller responds accordingly by updating the view. But delegation is still used in long-running, dynamic interactions such as a table view that displays the contents of a frequently updating data set (see NSFetchedResultsController).

As to your question of having the controller be the delegate of your view and your model, there's no inherent problem other than you'll degrade the cohesion of your controller, and it sometimes becomes a good choice to split the controller layer into view controllers and data controllers. Using KVO or NSNotification to observe changes in the model layer is usually straightforward enough that you won't find a pressing need to extract a new class.

Related Topic