12

I’ve always thought I understood MVC, but lately, after reading a lot of Stack Overflow posts on the subject, I’ve discovered that the ways in which MVC frameworks do things are slightly different from one another. More specifically, in the way in which the view and model interact, there seems to be two schools of thought:

  1. When the user interacts with the view, the view notifies the controller, and the controller in turn does something to the model. When the model changes, the model notifies the controller, which in turn updates the view.

  2. The view subscribes to the model. When the model changes, the view seems to be notified directly that it needs to update itself.

enter image description here

So my question is: In Cocoa Touch (iOS), what is the best way to do MVC? I’m mainly coding for iOS these days and am interested in the best practice for this platform only. (I’m not interested in how ASP.NET, Rails, Backbone, etc. do things.)

It would be wonderful if some KVO example code could be provided. Thanks. =)

Ben Klein
  • 1,719
  • 3
  • 18
  • 41
Louis Nguyen
  • 304
  • 2
  • 12

3 Answers3

5

Apple advocates use of the first method, I believe.

It is the modified version of the standard MVC model (the second approach), where model and view are totally separated. Personally I think that it’s cleaner and more extensible.

  1. The logic is centralized in the controller.
  2. There is no need to write custom views to handle events from the model. Normally you’d write a custom controller but use the view classes given by the SDK. Following the second method, you might have to create a custom view just to handle events from the model.
Ben Klein
  • 1,719
  • 3
  • 18
  • 41
hdoan
  • 382
  • 1
  • 10
3

I found that the best basic theory on the matter is taught in Stanford University by a very talented teacher named Paul Haggarty. I recommend looking this course up on iTunes U - there are 18 lectures in HD video and ppt files to learn from. Here is a link to the course website: http://www.stanford.edu/class/cs193p/cgi-bin/drupal/

I remember that he goes through the MVC part of the material very quickly but thoroughly, making this matter very clear. Also, I would have to say that the #1 school of thought is the one I agree more with.

Stavash
  • 14,244
  • 5
  • 52
  • 80
1

In my experience, (1) should be used in most cases.

In (2), since view does not own the model, you always need to pass the changes from model to view to be rendered and if a view could be update from multiple models, you need to write separate code for that.

In (1), the method to update the view from controller could be used by multiple models, controller has reference to models thus you don't need to pass any information in the notification.

Performance wise I don't know if there's any different but the code in (1) would be a lot clearer.

jasondinh
  • 918
  • 7
  • 21