I have been following a number of tutorials and i am falling down with self. Can anyone help please?
I have the following init, which is an instance method.
- (id) initWithScore:(int) s {
self = [super init];
if (self) {
score = s;
}
return self;
}
Now reading through the code i set the self to the super init, hence self is now pointing to super. I then check if self is valid and set score equal to the value i sent on my InitWIthScore. I have got this so far.
But now i return self which points to the super, so how am i returning my subclass?
Hence, lets say that somebody calls my class passing in 100, my code is returning the super not the class so how does it work? How does the calling code have value of 100 in score?
of course, yes it does work but i have no idea why 🙁
This construct allows the initializer (both the
superinitializer and the one you are writing) with a way of failing –nilis returned if the object cannot be initialized. That is also why you check fornilin yourinitafter callingsuper.Both
selfandsuperpoint to the same data structure in memory, namely your object that you have allocated. The difference is in the language semantics of these special pointers:When
selfis used, the Objective-C compiler will start method and overload resolution at your current type.When
superis used, the Objective-C compiler will start method and overload resolution at the immediate super type of your class. In other words,superis just semantics for being able to call a method in your super class even though the same method exists in your current class.In other words (slightly simplified),
supertreats the memory location as if it were an instance of the super class (e.g. the type you subclassed, oftenNSObject), whileselftreats the memory location as a regular pointer to the type you have defined.If you print
superandselfin the debugger, you will see they point to the same memory location.