在alloc init之后释放合成属性

时间:2012-01-09 08:35:54

标签: objective-c

我有一个属性

//.h
@property (nonatomic, retain) SomeCLass * someSynthInstance;
//.m
@synthesize someSynthInstance = _someSynthInstance;

- (void) foo 
{
    self.someSynthInstance = [[SomeCLass alloc] init];
    //[self.someSynthInstance release]; <- SHOULD I RELEASE HERE???
}

- (void) dealloc 
{
    self.someSynthInstance = nil;
}

我的理论认为,[alloc,init]创建一个计数1,并且setter,inc计数,因此它变为2,因此我应该在它之后立即释放它

但是我改变了这样的一切之后,目标是在应用程序中获取exc_bad_access,所以目标不确定它是否正常

4 个答案:

答案 0 :(得分:4)

您希望释放实例变量而不是属性。所以你可以这样做:

self.someSynthInstance = [[[SomeCLass alloc] init] autorelease]; // puts it in the autoreleasepool so it'll get released automatically at some point in the near future

_someSynthInstance = [[SomeCLass alloc] init]; // skip the property

self.someSynthInstance = [[SomeCLass alloc] init];
[_someSynthInstance release]; // call release on the instance variable

答案 1 :(得分:3)

标准做法是:

SomeClass *tmpObj = [[SomeClass alloc] init];
self.someSynthInstance = tmpObj;
[tmpObj release];

答案 2 :(得分:2)

你应该发布类变量,而不是像[_someSynthInstance release];那样应该做的。

答案 3 :(得分:1)

是的,你应该在init之后发布

SomeCLass *temp = [[SomeCLass alloc] init];
self.someSynthInstance = temp;
[temp release]