为什么在构造函数中释放会导致 EXC_BAD_ACCESS?
Why releasing in constructor cause EXC_BAD_ACCESS?
我有以下 class 构造函数
- (id)initForBlurringWithConstantMaskWithID:(int)maskid andSize:(CGSize)s{
self = [super init];
if (self) {
// some code
CGImageRef maskRef = [maskUI CGImage];
//Some code where maskRef is used
CGImageRelease(maskRef); // I won't ever use it again
}
return self;
}
但是,当使用 ARC 释放对象时(在我看来),所有内容都会因 EXC_BAD_ACCESS(代码=EXC_i386_GPFLT)而崩溃,通常在访问 "wrong" 地址时调用.
如果我删除发布行,一切正常。不管怎样,谁能解释为什么会这样?
我的猜测是 ARC 也在尝试删除 maskRef,但找不到它并导致崩溃。
您只需在创建(CGImageCreate)、复制或保留对象时调用CGImageRelase。 [maskUI CGImage]
未声明新所有权,因此您不负责释放它。
解决方法:
下降 CGImageRelease(maskRef);
我有以下 class 构造函数
- (id)initForBlurringWithConstantMaskWithID:(int)maskid andSize:(CGSize)s{
self = [super init];
if (self) {
// some code
CGImageRef maskRef = [maskUI CGImage];
//Some code where maskRef is used
CGImageRelease(maskRef); // I won't ever use it again
}
return self;
}
但是,当使用 ARC 释放对象时(在我看来),所有内容都会因 EXC_BAD_ACCESS(代码=EXC_i386_GPFLT)而崩溃,通常在访问 "wrong" 地址时调用.
如果我删除发布行,一切正常。不管怎样,谁能解释为什么会这样?
我的猜测是 ARC 也在尝试删除 maskRef,但找不到它并导致崩溃。
您只需在创建(CGImageCreate)、复制或保留对象时调用CGImageRelase。 [maskUI CGImage]
未声明新所有权,因此您不负责释放它。
解决方法:
下降 CGImageRelease(maskRef);