【问题标题】:Under Automatic Reference Counting (ARC), where do I put my free() statements?在自动引用计数 (ARC) 下,我应该将 free() 语句放在哪里?
【发布时间】: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


【解决方案1】:

你是对的,你必须实现dealloc并在其中调用freedealloc 将在对象像 ARC 之前一样被释放时被调用。此外,您不能致电[super dealloc];,因为这将自动完成。

最后注意,可以使用NSDatafilled分配内存:

self.filledData = [NSMutableData dataWithLength:size.x * size.y * size.z];
self.filled = [self.filledData mutableBytes];

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

【讨论】:

    【解决方案2】:

    是的,你把它放在-dealloc 中,就像你在 MRR 下一样。与-dealloc 的唯一区别是您不能调用[super dealloc]。除此之外,它完全一样,并且在对象完全释放时被调用。


    顺便说一句,free() 将接受NULL 指针并且什么都不做,所以你实际上不需要-dealloc 中的条件。你可以说

    - (void)dealloc {
        free(filled);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-29
      • 1970-01-01
      • 2020-09-30
      • 2020-08-11
      • 1970-01-01
      • 2017-11-06
      相关资源
      最近更新 更多