我是一个新手,正在尝试使用 XCode 为一个非常简单的 Mac 应用程序组合一个非常简单的界面。
我尽可能地精简了我的应用程序,以说明我遇到的问题。
我当前的界面由一个按钮组成。
在我的 AppController.h 文件中,我有以下内容:
@interface AppController : NSObject
{
NSMutableArray *ages;
int price;
NSString *culler;
}
-(IBAction) handleButtonClick: (NSButton*)sender;
@end
在我的 AppController.m 文件中,我使用我的 awakeFromNib 方法设置初始值:
-(void)awakeFromNib
{
ages = [NSMutableArray arrayWithObjects: nil];
[ages addObject: [NSNumber numberWithInt: 10]];
[ages addObject: [NSNumber numberWithInt: 21]];
price = 45;
culler = [NSString stringWithString: @"bright green"];
NSLog(@"waking up from nib, ages contains %i objects",[ages count]);
NSLog(@"they are ...");
for(int i = 0; i<[ages count]; i++)
{
NSLog(@"%i", [[ages objectAtIndex: i] integerValue]);
}
NSLog(@"waking up from nib, the current price is %i", price);
NSLog(@"waking up from nib, the color is %@", culler);
}
一切似乎都运行良好,并且我收到了我期望的日志消息。
但是在我处理单个按钮点击的方法中,我有以下内容:
-(void) handleButtonClick: (NSButton*) sender
{
NSLog(@"you clicked the button");
NSLog(@"after clicking the button, the current price is %i", price);
NSLog(@"after clicking the button, the color is %@", culler);
NSLog(@"after clicking the button, ages contains %i objects",[ages count]);
NSLog(@"they are ...");
for(int i = 0; i<[ages count]; i++)
{
NSLog(@"%i", [[ages objectAtIndex: i] integerValue]);
}
}
当我点击按钮时,我收到日志消息,告诉我‘culler’和‘prices’包含的正是我所期望的(= 正是我在‘awakeFromNib’中给它们的值)但是程序随后吐出一个“程序收到信号:“EXC_BAD_ACCESS””消息,沙滩球出现,好像它不喜欢我提到我的‘年龄’数组。
这里显然有一些我不理解的基本知识。 我可以引用我的 int 和我的 NSString 但不能引用我的 NSMutableArray?
我很困惑。
如果有人能指出正确的方向,我将不胜感激。
感谢您阅读本文。
最佳答案
您正在使用 arrayWithObjects
初始化您的数组。请注意,此方法返回一个 autoreleased 对象,该对象在您的 awakeFromNib
结束后可能无效。
要么添加一个retain
消息:
ages = [[NSMutableArray arrayWithObjects:nil] retain];
或者使用不会返回自动释放对象的方法,例如默认的alloc
和init
方式:
ages = [[NSMutableArray alloc] initWithObjects:nil];
并且一定要阅读 Memory Management Guide .
关于objective-c - 新手对 NSMutable 数组的行为感到迷惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6849259/