iphone - Returning nil in the init in Objective C code -
in case, if return nil in init method, what's happening retain count , going release object?
as undertand called alloc (which happen before init), retain count become 1. now, init called , let reason can't initialize object, returns nil.
and looks have object retain count equal 1 , nobody has reference call release.
should call [self autorelease] in init such case or else?
see allocating , initializing objects in documentation.
specifically, if have error in initializer, release
self
, return nil
:
- init { self = [super init]; if (self) { if (... failed initialize in self ...) { [self release]; return nil; } } return self; }
now, consider happens when call [super init]
, returns nil
. above pattern has been employed, self
has been released, , nil
return indicates instance gone. there no leak , happy.
this valid pattern (assume self
instance of myclass
):
- init { self = [super init]; if (self) { ... normal initialization here ... } else { self = [myclass genericinstancewheninitializationgoesbad]; self = [self retain]; } return self; }
since init
expected return retained
(by implication of being chained +alloc
), [self retain]
, though looks goofy, correct. self = [self retain]
being defensive in case myclass
overrides retain
weird.
Comments
Post a Comment