This may be a dumb question, but in MVC the view doesn’t know about the model right. I’ve looked at some examples for table view cells, and the table view cell has a property of the model object. It then uses that model’s property to fill in the label, or the image for the cell.
Or in another case, if I have a UIView to draw something dynamically based on the model, it seems like it would be the easiest to have a property on the UIView so the UIView can access that model’s data in order to draw it dynamically. So I could do something like this:
myView.object = newObject;
[myView setNeedsDisplay];
Is this wrong for MVC? If so, what are the better ways to do these two things? Thanks.
So what would you have the view say to the model in order to get the right information? It has to know something about the model in order to ask the right question, right? Alternately, you could define a protocol like
UITableViewDataSourceand send generic messages like-cellForRowAtIndexPath:, and then implement that protocol in your model. That avoids the need for the view to know anything specific about the model, but it means instead that the model now has to know about the view — it has to know something about what’s supposed to be displayed in the view so that it can pass back the right data. Whichever way you go, you introduce a dependency between the model and the view, and that means that when you make a change in one you’ll have to make a change in the other.Avoiding those kinds of dependencies is exactly the point of the MVC architecture. The controller knows about both model and view, which allows the model and view to exist independent of each other.
It might sometimes make sense to have some objects that both model and view know about. If you’re writing an address book, it might make sense to have a ContactView that knows how to display a Contact, and a model that stores Contact objects. That seems much more sensible than having a view that’s completely stupid about what it’s displaying, and it lets you pass around Contact objects instead of great long lists of name, address, phone, fax, email, etc. You could say that a Contact is a model object, and all the above applies: you’ll be introducing a dependency between ContactView and Contact. But usually when we talk about “the model”, we mean the whole graph of objects that the program uses to store its data, and the benefit of MVC is to separate the way you manage all those objects from the way you present the data that they contain.