我应该总是释放自己失败的init方法? [英] Should I always release self for failed init methods?
问题描述
我应该总是在init里面发生故障时释放自我,或者如果我先初始化了实例变量,我应该怎么做?
Should I always release self when there is a failure inside init, or should I only do so if I have initialized instance variables first?
,这个模式有效吗?有没有时间,我不应该在init方法中释放self,或者我应该假设如果控制流进入init,self至少有一个保留计数1?
To put it another way, is this pattern valid? Is there a time when I shouldn't release self inside an init method, or should I assume that if the control flow enters init, self has at least a retain count of 1?
- (id)init
{
if ((self = [super init]) == nil)
{
[self release];
return nil;
}
//do some init stuff
if (somethingFailed)
{
[self release];
return nil;
}
return self;
}
推荐答案
你的初始化方法失败,那么你应该释放 self
。注意,如果 [super init]
返回 nil
,发送发布到 self
as self
是 nil
。这实际上是苹果所皱眉的:
If some check you need in your initialization method fails, then yes you should release self
. Note however, that if [super init]
returns nil
it does not make sense to send release to self
as self
is nil
. This is actually frowned on by Apple:
你应该只调用
[self release]
在故障点。如果从调用超类的初始化器得到nil
,你不应该调用release
。
You should only call
[self release]
at the point of failure. If you getnil
back from an invocation of the superclass’s initializer, you should not also callrelease
.
示例:
- (id)init
{
self = [super init];
if(self) {
// do some init stuff
if (somethingFailed)
{
[self release]
self = nil;
}
}
return self;
}
另请参阅Mac开发中心文档处理初始化失败
Also see the Mac Dev Center documentation on Handling Initialization Failure
这篇关于我应该总是释放自己失败的init方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!