【发布时间】:2012-03-30 06:29:37
【问题描述】:
在 cocoa 中,ARC 让您不必担心保留、释放、自动释放等。它还禁止调用 [super dealloc]。允许使用 -(void) dealloc 方法,但我不确定是否/何时调用它。
我知道这对于对象等来说都很棒,但是我在哪里放置与 malloc() 匹配的 free() 我在 -(id) init 中所做的?
例子:
@implementation SomeObject
- (id) initWithSize: (Vertex3Di) theSize
{
self = [super init];
if (self)
{
size = theSize;
filled = malloc(size.x * size.y * size.z);
if (filled == nil)
{
//* TODO: handle error
self = nil;
}
}
return self;
}
- (void) dealloc // does this ever get called? If so, at the normal time, like I expect?
{
if (filled)
free(filled); // is this the right way to do this?
// [super dealloc]; // This is certainly not allowed in ARC!
}
【问题讨论】:
-
free(0)是空操作,所以free(filled)是写if (filled) free(filled);的更简单的方式。 (我看到另一位海报在下面写了这个,但它不在接受的答案中,所以我想我也会把它留在这里。)
标签: objective-c cocoa free automatic-ref-counting dealloc