Possible Duplicate:
In Objective-C why should I check if self = [super init] is not nil?
I’m new at Ob-C, and am having a hard time understanding why the value returned is non-nil as tested by the “if statement”.
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
This method invokes the parent initializer first. Executing the parent’s initializer ensures that any inherited instance variables are properly initialized.
You must assign the result of executing the parent’s init method back to self because an initializer has the right to change the location of the object in memory (meaning its reference will change).
If the parent’s initialization succeeds, the value returned will be non-nil, as tested by the if statement. As the comment indicates, inside the block that follows is where you can put your own custom initialization code for your object. This will often involve allocating and initializing instance variables that are in your class.
Pasted code and text from
From Stephen Kochan “Programming in Objective-C, Fourth Edition”
Consider the following scenario, you have a parent class, which we’ll call
Parent, that has the following layout:and you have a class
Child, which is a subclass ofParent, and has the following layout:within the
Childsubclass, you have no direct access to theParentivar calledvalue. However, in its initialization,Parentassigns some integer tovalue, and some functionality inParentdepends on this value being set.if
Childdoes not call[super init],valuewill never be initialized and part of the functionality ofParent, whichChildinherits, will be broken. Theinitmethod is defined to return a pointer to the initialized object instance. If you ignore the return value of[super init], you can get into trouble, because the parent init may have decided to reassign the object instance to some location other than the one provided by the allocator.For instance, NSString can detect initialization with empty string literals, and will return a pointer to a constant NSString reference instead of one on the heap. So say you just call
[super init]and ignore its return value, and keep using theselfpointer value passed to theChildsinitmethod, you’re suddenly using a dangling pointer!This is an extreme case, but the point is, if you intent to inherit functionality from your parent class, you should assign self to
[super init], and you should check if it returnsnilbecause it may have decided to fail initialization and destroy the memory provided to it by the allocator.