在自动引用计数(ARC)下,我在哪里放置我的free()语句?

Oli*_*lie 4 free cocoa objective-c dealloc automatic-ref-counting

在可可中,ARC使您不必担心保留,释放,自动释放等.它还禁止呼叫[super dealloc].-(void) dealloc允许一种方法,但我不确定是否/何时调用它.

我知道这对于对象等都是如此的好,但是我把free()它放在哪里与malloc()我所做的匹配-(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!
}
Run Code Online (Sandbox Code Playgroud)

sch*_*sch 14

你是对的,你必须实现dealloc并调用free它.dealloc将在ARC之前释放对象时调用.此外,你不能打电话,[super dealloc];因为这将自动完成.

最后,请注意您可以使用NSData以分配内存filled:

self.filledData = [NSMutableData dataWithLength:size.x * size.y * size.z];
self.filled = [self.filledData mutableBytes];
Run Code Online (Sandbox Code Playgroud)

执行此操作时,您不必显式释放内存,因为它将在对象中自动完成并因此filledData被释放.


Lil*_*ard 8

是的,你-dealloc就像在MRR下一样把它放进去.唯一的区别-dealloc是你不能打电话[super dealloc].除此之外,它完全相同,并且在对象完全释放时将被调用.


顺便说一下,free()接受NULL指针并不做任何事情,所以你实际上并不需要那个条件-dealloc.你可以说

- (void)dealloc {
    free(filled);
}
Run Code Online (Sandbox Code Playgroud)