Accessing the Controller Data Member in the Model Class

advertisements

I am using Xcode to develop a GUI application. I have a model class and a controller class. I have a NSTextView data member in my controller class. How do I access this variable from the model class?


First of all, a model class shall not talk to a view class. A TextView is part of the view.

alt text http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/Art/cocoa_mvc.gif

The controller talks to view classes and view classes provide feedback to the controller. The model classes get updated by the controller and provide feedback to it. The model classes never talk to a view class, they don't even know about the existence of any view classes. So I think you have a basic design problem here. You probably implemented MVC as in this model:

alt text http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/Art/traditional_mvc.gif

However this is not the way it is done in Mac OS X, this is not the way Apple does it and this is not the way how the whole Cocoa object structure has been designed! So the answer to your question is: You don't, because you should not.

Aside from the fact, that you have a design flaw, you access it like you access all data members in Objective-C. If it is public, you can access it directly:

MyController * c = [[MyController alloc] init];
// c has a member name textView, let's access it
[c->textView ...];

You should already know, that this is actually very bad programming style. You should not access data members of another object directly. You should actually not even make them public. If you declare them private, the code above will fail (the compiler enforces that you don't do this). The other way is to implement a getter and access it via the getter:

// This goes into the controller

- (NSTextView) textView
{
    return textView;
}

// This is called in the modell

[[c textView] ...];

However, this is also bad design. The model might do whatever it wants with this object and your controller won't see it! Why doesn't you model just tell the controller what it wants to happen?

// In the controller

- (void) notifyContentHasChanged:(NSString *)name
{
    // update the text view here ...
}

// In the modell

[c notifyContentHasChanged:...];

And voila, you have MVC the way Apple wants it to be. The model only notifies the controller of what's going on and the controller updates the view accordingly.