I am currently populating an NSTableView through the controller (MVC design pattern) where I initialise one entry of a NSMutableArray in the controller’s init method.
How would I:
- Populate my NSMutableArray which is an array of Person objects
- Should I populate the NSMutableArray in my
mainViewDidLoadmethod of my base class instead? I have not found any examples or resources for this.
Model (Person.m)
#import "Person.h"
@implementation Person
@synthesize name;
@synthesize gender;
- (id)init
{
self = [super init];
if (self) {
name = @"Bob";
gender = @"Unknown";
}
return self;
}
- (void)dealloc
{
self.name = nil;
self.gender = nil;
[super dealloc];
}
@end
Controller (PersonController.m)
#import "PersonController.h"
#import "Person.h"
@implementation PersonController
- (id)init
{
self = [super init];
if (self) {
PersonList = [[NSMutableArray alloc] init];
// [personList addObject:[[Person alloc] init]];
//
// [personTable reloadData];
}
return self;
}
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
return [personList count];
}
- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
Person *person = [personList objectAtIndex:row];
NSString *identifier = [tableColumn identifier];
return [person valueForKey:identifier];
}
- (void)dealloc
{
[super dealloc];
}
@end
Base file (Main.h):
#import "Main.h"
@implementation Main
- (void)mainViewDidLoad
{
}
@end
Step 1: Create Person objects.
Step 2: Add them to the array.
Your commented-out code does exactly this, although you should probably create the Person separately in case you want to configure it (e.g., set its name).
It doesn’t really matter how far in advance of the user seeing your model you create it, but conceptually, it kind of smells to me. It doesn’t have anything to do with the view, so I say it belongs in
init.Of course, if the main view—and every view in it—has already loaded, you’ll need to tell the table view to reload your data to get it to show any changes you made to the array. Conversely, if you create the model before loading the view, you don’t need to reload initially, because the table view will have already asked you for your model once.