Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning nil in the init in Objective C code

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?

like image 399
Victor Ronin Avatar asked Dec 02 '10 15:12

Victor Ronin


People also ask

How do you find nil in Objective C?

Any message to nil will return a result which is the equivalent to 0 for the type requested. Since the 0 for a boolean is NO, that is the result. Show activity on this post. Hope it helps.

What is init in Objective C?

init() Implemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated.


1 Answers

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.

like image 129
bbum Avatar answered Oct 10 '22 19:10

bbum