New to objective-c. Wrote a code-snippet to better understand the init mechanism, and ended up with a few questions.
@implementation MyClass
-(id) init
{
if (self) {
i = 5;
NSLog(@"self before init - %@ %p i=%d",[self className], &self, i);
} else {
NSLog(@"self is null???");
}
id someClass = [super init];
NSLog(@"the result of super-init - %@ %p",[someClass className], &someClass);
self = [super init];
if (self) {
NSLog(@"self after init - %@ %p %d",[self className], &self, i);
} else {
NSLog(@"self is null???");
}
return self;
}
i is a private instance variable int.
Here is the result:
2012-12-14 18:01:26.403 Init[1621:303] self before init - MyClass 0x7fff5fbff848 i=5
2012-12-14 18:01:26.405 Init[1621:303] the result of super-init - MyClass 0x7fff5fbff838
2012-12-14 18:01:26.405 Init[1621:303] self after init - MyClass 0x7fff5fbff848 5
What really surprised me is that that someClass’s class Name is MyClass.
- How does
NSObjectknow to return the sub-classes instance (not just the type match, it is the exact same object)?
I’m aware that it is not good form to call init many times, and initialize instance variables before calling init but I was just experimenting.
Thanks.
You do need to use the standard schemen (more or less):
Your class subclasses some other class. The call to
super initruns the init routine of your superclass. Without it your class is not properly initialized and may malfunction strangely. (However, it’s probably not wise to callsuper inittwice, as this could have bad side-effects.)There are cases where you would not call
super init, but would instead call a version ofinitin your own class. Basically, if you haveinitWithJunk:andinit, you can haveinitWithJunk:call[self init]instead of[super init]so that the stuff thatself initwould do gets done and doesn’t have to be reproduced ininitWithJunk:.This is especially critical if you write a “category” that adds an
init...method to an existing class — you must call some version of[self init]to assure that the base class’s initializer runs.Understand that the
super initmethod is not (usually) replacing the existing instance with a new one, but rather is initializing instance fields in it that belong to the superclass. The reason for receiving the “self” value back from thesuper initcall is two-fold:nilin the event that some sort of error occurs.