I’m working on my first cocoa app from scratch and I’m a little confused about how to get my model, view, and controller working together. I’m sure I’m just missing something inane.
Basically, my view is currently set up to return 3 values to the controller. The controller takes those values and creates a new instance of a class. I want to be able to put those objects in an array and then work with the array.
First: The array I want to create… it is my model, right? How and where do I create it so that an action in the view (inputing the values) is interpreted by the controller correctly (creating the object) and then stored in the method?
Second: The attempts I have made leave me isolated from my array. I tried to create a class for the array, but I can’t access it from the controller. How do I get around this?
Lastly: I’ve been banging my head against the code for a few days. I’m teaching myself and I’m learning a lot but I have lots of simple questions like this. Thank you for taking the time to help. )
EDIT:
I’ve created the Student class. The Action sends the values to the controller and the controller creates a new instance:
- (IBAction)addNewStudentButtonPressed:(id)sender
{
Student *newStudent = [[Student alloc] initNewStudentwithName:[nameField stringValue]
andID:[idField intValue]
andLevel:[levelField stringValue]];
}
The Array is being created in the appDidFinishLaunching method:
-(void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSMutableArray *roster = [[NSMutableArray alloc] initWithCapacity:100];
}
And now I want to add the student to the array. I’m just missing something obvious. 🙁
Think of the model as an active representation of what your program is dealing with – you need to show a list of students? Then you have to design a
Studentclass with a bunch of properties [like I smell you already did].The controller acts as a bridge between the user and the model, and this connection is the view: you hit a button in the view, and you want a new student to be created therefore, and to be added to an array then.
First, you need an array: you provide your Controller with such property/ivar – I’ll stick with ivar in this example:
AppDelegate.h
AppDelegate.m
The array is part of the logic, but not of the model itself – it’s just a controller basic field at the moment. Of course if you define a
Classroomclass with a list of students, you are wrapping the array inside another entity.Anyway the MVC matter is quite loose, and has many implementations – don’t let it overhelm you, just let the pattern help you to separate concerns and to have a smoother development, but don’t think of it as a dogma.