I am trying to add a class object to an NSMutableArray but the object appears to be out of scope after adding it.
interface:
#import <Cocoa/Cocoa.h>
@class Person;
@interface MyDocument : NSDocument
{
NSMutableArray *employees;
IBOutlet NSTableView *raiseTableView;
}
- (IBAction)createEmployee:(id)sender;
- (IBAction)deleteSelectedEmployees:(id)sender;
@end
Part of the .m file:
#import "MyDocument.h"
#import "Person.h"
@implementation MyDocument
- (id)init
{
self = [super init];
if (self) {
employees = [[[NSMutableArray alloc] init]retain];
}
return self;
}
- (IBAction)createEmployee:(id)sender
{
Person *newEmployee = [[Person alloc] init];
[employees addObject:newEmployee];
NSLog(@"personName is: %@, expectedRaise is: %f", newEmployee.personName, newEmployee.expectedRaise);
[newEmployee release];
[raiseTableView reloadData];
}
The NSLog prints everything correctly. When I look at employees it shows 1 object added, when I look at the object it has a notation that it is out of scope and when I try to print it I get null for a result. Consequently, when it tries to reloadData things blow up. Anyone give me a hint as to what I am forgetting? Thanks.
TableView code:
#pragma mark Table view datasource methods
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tempTableView
{
return [employees count];
}
- (id)tableView:(NSTableView *)tempTableView objectValueForTableColumn:(NSTableColumn *)tempTableColumn row:(NSInteger)rowIndex
{
// What is the identifier for the column?
NSString *tempIdentifier = [tempTableColumn identifier];
// What person?
Person *tempPerson = [employees objectAtIndex:rowIndex];
// What is the value of the attribute named identifier?
return [tempPerson valueForKey:tempIdentifier];
}
- (void)tableView:(NSTableView *)tempTableView setObjectValue:(id)anObject forTableColumn:(NSTableColumn *)tempTableColumn row:(NSInteger)rowIndex
{
NSString *tempIdentifier = [tempTableColumn identifier];
Person *tempPerson = [employees objectAtIndex:rowIndex];
// Set the value for the attribute named identifier
[tempPerson setValue:anObject forKey:tempIdentifier];
}
employees? Everything seems fine here. Anywhere else except thecreateEmployeemethod thenewEmployeewould be out of scope so I'm wondering where do you access it and get out of scope?employees. You don't need to sendretain; the fact that you havealloced it already means you own it.