Cœu*_*œur 0 release objective-c init self
我有一个自定义的非ARC初始化,我想知道[super init]在释放自我之前是否应该打电话.
解决方案A,[super init]之前没有调用[self release]:
- (instancetype)initWithInteger:(NSInteger)anInteger
{
if (anInteger == 0)
{
[self release];
return nil;
}
self = [super init];
if (!self)
return nil;
// Initialization code
self.i = anInteger;
return self;
}
Run Code Online (Sandbox Code Playgroud)
解决方案B,[super init]之前调用[self release]:
- (instancetype)initWithInteger:(NSInteger)anInteger
{
self = [super init];
if (!self)
return nil;
if (anInteger == 0)
{
[self release];
return nil;
}
// Initialization code
self.i = anInteger;
return self;
}
Run Code Online (Sandbox Code Playgroud)
我会选择第二种模式.这样做的原因是super的dealloc可能依赖于super的init中的某些东西来完成正常工作.
这是一个(非常)人为的例子,这是你正在子类化的类中的init和dealloc方法.
@implementation ASuperClass
{
char* foo;
}
-(id) init
{
self = [super init];
if (self != nil)
{
foo = strdup("blah blah blah");
}
return self;
}
-(void) dealloc
{
if (foo[1] == 'l')
{
NSLog(@"Second character was l");
}
free(foo);
}
Run Code Online (Sandbox Code Playgroud)
在上面,如果这是您继承的类,则您的第一个模式将在空指针取消引用上抛出EXC_BAD_ACCESS.
| 归档时间: |
|
| 查看次数: |
140 次 |
| 最近记录: |