【发布时间】:2010-11-14 14:06:58
【问题描述】:
在我的 iPhone 应用程序中,构造函数中有以下行:
self.myVar = myVar_in;
其中 myVar 是属性,myVar_in 是传递给构造函数的参数。
当我运行代码时,我在这一行收到 EXC_BAD_ACCESS 错误。但是,当我将行替换为:
[myVar release];
[myVar_in retain];
myVar = myVar_in;
代码运行良好。我的财产是这样声明的: NSNumber *myVar; ... @property (retain) NSNumber *myVar;
错误是一致的,我很肯定这不是变量范围问题。有人可以解释这种行为吗?
编辑:我已经确认 myVar_in 在行执行之前有效。这是实际的代码,虽然它没有多大帮助:
-(GetAddressRequestHelper*)initWithRequest:(ClientRequest*)request delegate:(id<ServerResponseDelegate>)delegate number:(NSNumber*)myVar_in location:(CLLocation*)location {
self = [super initWithRequest:request delegate:delegate];
if( self ) {
// same behavior even if this line is uncommented!!!
myVar_in = [NSNumber numberWithInt:123];
// prints "myVar_in is 123"
NSLog(@"myVar_in is %@",myVar_in);
// doesn't throw exception
/*[myVar release];
[myVar_in retain];
myVar = myVar_in;*/
// throws exception
self.myVar = myVar_in;
self.location=location;
}
return self;
}
EDIT2:我发现当我使用myVar_in = [NSNumber numberWithInt:123]; 显式初始化参数时,我仍然会遇到这种行为!
谢谢
【问题讨论】:
-
作为一个小提示,最好在释放旧对象之前保留新对象,以防它们实际上是同一个对象。
-
@Quinn:谢谢,我忘记了。
-
@Quinn:完全正确,虽然我之前尝试过,但不适用于这种情况
标签: iphone objective-c cocoa cocoa-touch properties