See Allocating and Initializing Objects in the documentation.
Specifically, if you have an error in your initializer, then you release
self
and return nil
:
- init
{
self = [super init];
if (self) {
if (... failed to initialize something in self ...) {
[self release];
return nil;
}
}
return self;
}
Now, consider what happens when you call [super init]
and it returns nil
. The above pattern has already been employed, what was self
has been released, and the nil
return indicates that the instance is gone. There is no leak and everyone is happy.
This is also a valid pattern (assume that self
is an instance of MyClass
):
- init
{
self = [super init];
if (self) {
... normal initialization here ...
} else {
self = [MyClass genericInstanceWhenInitializationGoesBad];
self = [self retain];
}
return self;
}
Since init
is expected to return something that is retained
(by implication of being chained from +alloc
), then that [self retain]
, though it looks goofy, is actually correct. The self = [self retain]
is just being extra defensive in case MyClass
overrides retain
to do something weird.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…