gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:56:02 26 4
gpt4 key购买 nike

在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com