I set up a project using MVC (to be more specific this is Hello Poly part 2 from Stanford)
and I’m having problems referencing object.
So I have Model which is PolygonShape class, Controller – controller, and View – PolygonView.
I made outlets in Controller :
IBOutlet PolygonShape *myShape;
IBOutlet PolygonView *myView;
and in implementation in awakeFromNib I initialize myShape
myShape = [[PolygonShape alloc] initWithNumberOfSides:x minimumNumberOfSides:3 maximumNumberOfSides:12];
and then I want in View somehow know about
myShape.numberOfSides
Inside interface of PolygonView i have
IBOutlet PolygonShape *myShape;
and
@property (retain) PolygonShape *myShape;
but what happens is actually myShape in PolygonView is not the same object, even though I think I have proper connections set up in Interface Builder
Following MVC directions I can’t make model to comunicate directly with the view, so how can I access myShape from PolygonView ??
First of all, PolygonView’s myShape should not necessarily be an IBOutlet, and neither should PolygonShape’s myShape. In awakeFromNib (of the controller), just under what you have now, add
It is perfectly acceptable for a view to know about the model, just not the other way around. So in PolygonView, it is perfectly acceptable to say
myShape.numberOfSides, because after all it has a pointer to a PolygonShape, and therefore ‘knows about’ PolygonShapes, and all their methods. If you are worried about how myView is going to know about changes to myShape, you simply need to call a method like-[PolygonView setNeedsDisplay:YES], or for something a little bit more in involved, write a refresh method or something in that vein. Basically, the idea of Model-View-Controller in the first place is that all interactions should be going through the Controller anyway, so whenever it updates the Model, it also just tells the relevant Views to refresh. (Some of this gets much easier with bindings, btw, but that’s only available on MacOS for the time being.)