Populate employees array at start?


#1

I finished the RaiseMan project in Chapter 8. Decided I would like it come up initially already populated with some values (Person objects).

So in RMDocument.xib window I created a Referencing Outlet in my RMDocument.h file from the Array Controller:

@property (strong) IBOutlet NSArrayController *arrayControllerOutlet;

In RMDocument.m I first synthesized it:

@synthesize arrayControllerOutlet;

Then I added this code (using the Xcode provided method) windowControllerDidLoadNib except for the very last line:

  • (void)windowControllerDidLoadNib:(NSWindowController *)aController
    {
    [super windowControllerDidLoadNib:aController];
    // Add any code here that needs to be executed once the windowController has loaded the document’s window.
    Person *p1 = [[Person alloc] init];
    [p1 setPersonName:@“John Smith”];
    [p1 setExpectedRaise:0.06];
    [employees addObject:p1];
    Person *p2 = [[Person alloc] init];
    [p2 setPersonName:@“Jane Doe”];
    [p2 setExpectedRaise:0.065];
    [employees addObject:p2];
    [arrayControllerOutlet didChangeArrangementCriteria];
    }

When I first tried it the employees didn’t show up until I added a New Person. Then I searched around and added the very last line above:

[arrayControllerOutlet didChangeArrangementCriteria];

That gets the Array Controller to make the TableView display these Persons right away.

My question is, is this a reasonable thing to do, or is there something better?


#2

Since you are using bindings, probably better to send out KVO messages
[self willChangeValueForKey:@“employees”] and [self didChangeValueForKey:@“employees”]:

- (void)windowControllerDidLoadNib:(NSWindowController *)aController
{
     [super windowControllerDidLoadNib:aController];
     // Add any code here that needs to be executed once the windowController...

     [self willChangeValueForKey:@"employees"];

     Person *p1 = [[Person alloc] init];
     [p1 setPersonName:@"John Smith"];
     [p1 setExpectedRaise:0.06];
     [employees addObject:p1];
     Person *p2 = [[Person alloc] init];
     [p2 setPersonName:@"Jane Doe"];
     [p2 setExpectedRaise:0.065];
     [employees addObject:p2];

     [self didChangeValueForKey:@"employees"];
}

You could also try using one of array controller’s addObjects: and setContent: methods.


#3

Thanks! That works. I will need to research why. Thanks again.