Out of scope error when adding an object to an NSMutableArray
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];
}
I think it's crashing because this line:
NSString *tempIdentifier = [tempTableColumn identifier];
is returning a null for tempIdentifier, so that the null string is getting passed to the Person class here:
NSString *tempIdentifier = [tempTableColumn identifier];
Which is causing the error message. You should print out the value of tempIdentifier to be sure.
Did you set the identity field for each column in your TableView in InterfaceBuilder?
精彩评论