In the case, if we return nil in the init method, what's happening with retain count and who is going to release this object?
As I undertand as soon as we called alloc (which will happen before init), the retain count will become 1. Now, init is called and let say for some reason it can't initialize the object, so it returns nil.
And it looks like now we have the object with retain count equal 1 and nobody has reference to it to call release.
Should we call [self autorelease] in init for such case or do something else?
Best Answer
See Allocating and Initializing Objects in the documentation.
Specifically, if you have an error in your initializer, then you
release
self
and returnnil
:Now, consider what happens when you call
[super init]
and it returnsnil
. The above pattern has already been employed, what wasself
has been released, and thenil
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 ofMyClass
):Since
init
is expected to return something that isretained
(by implication of being chained from+alloc
), then that[self retain]
, though it looks goofy, is actually correct. Theself = [self retain]
is just being extra defensive in caseMyClass
overridesretain
to do something weird.