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

标签 objective-c cocoa free automatic-ref-counting dealloc

在 cocoa 中,ARC 使您不必担心 retain、release、autorelease 等。它还禁止调用 [super dealloc]。允许使用 -(void) dealloc 方法,但我不确定是否/何时调用它。

我知道这对对象等来说是多么棒,但是我应该把 free() 放在哪里,它与我在 中所做的 malloc() 相匹配>-(id) 初始化 ?

例子:

@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!
}

最佳答案

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

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

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

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

关于objective-c - 在自动引用计数 (ARC) 下,我应该在哪里放置我的 free() 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9691092/

相关文章:

objective-c - NSPerformService "Tweet"与图像 (Twitter.app)

objective-c - 将 nsarraycontroller 绑定(bind)到 nsobjectcontroller、选择、内容的编程等效项

c - 自由(): invalid next size (fast) in C

iphone - IOS 是否支持所有 Unicode 表情符号?

ios - 从 iOS 上传图片到 PHP 服务器

iphone - 计算 MKPolyline 路径的距离?

objective-c - 如何将 NSString 从 CamelCase 转换为 TitleCase, 'playerName' 转换为 'Player Name'?

objective-c - Obj-C/Cocoa : Use of Shortcut Recorder Framework, 怎么办?

C : freeing a reallocated pointer

c - 应该在 longjmp() 之后调用 free() 吗?