【发布时间】:2011-09-18 17:37:27
【问题描述】:
我正在尝试向 NSMutableArray 添加一个类对象,但添加后该对象似乎超出了范围。
界面:
#import <Cocoa/Cocoa.h>
@class Person;
@interface MyDocument : NSDocument
{
NSMutableArray *employees;
IBOutlet NSTableView *raiseTableView;
}
- (IBAction)createEmployee:(id)sender;
- (IBAction)deleteSelectedEmployees:(id)sender;
@end
.m 文件的一部分:
#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];
}
NSLog 可以正确打印所有内容。当我查看员工时,它显示添加了 1 个对象,当我查看该对象时,它有一个符号表明它超出了范围,当我尝试打印它时,我得到 null 的结果。因此,当它尝试重新加载数据时,事情就会爆炸。有人给我暗示我忘记了什么吗?谢谢。
表格视图代码:
#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];
}
【问题讨论】:
-
我不认为你试图解决的问题(reloadData 爆炸)是由这段代码引起的。当事情“爆炸”时,您会遇到什么错误?堆栈跟踪指向什么?你的 TableViewDelegate 是什么样子的?
-
你可以在你使用
employees的地方添加代码吗?这里一切似乎都很好。除了createEmployee方法之外的任何其他地方newEmployee将超出范围,所以我想知道您在哪里访问它并超出范围? -
cellForRowAtIndexPath 中可能存在一些问题,因为这里的代码目前似乎还可以。您能为我们提供更多项目的代码示例吗?
-
与您的问题无关,但您过度保留
employees。您无需发送retain;您拥有alloced 的事实已经意味着您拥有它。 -
@adpalumbo:这是我单击“创建新员工”按钮时收到的错误消息:2011-09-20 09:32:50.484 RaiseMan[7548:707] [
valueForUndefinedKey:]:这个类对键(null)不兼容键值编码。当我单步执行代码时,对象在添加到数组后超出范围,如果我打印数组,它会返回 null。这就是为什么我认为错误必须在这部分代码中。不确定 TableViewDelegate 的外观是什么意思。我与代表做了一些工作,但还没有完全理解他们。
标签: objective-c nsmutablearray