// A : Parent
@implementation A
-(id) init
{
// change self here then return it
}
@end A
A *a = [[A alloc] init];
a. Just wondering, if self is a local variable or global? If it’s local then what is the point of self = [super init] in init? I can successfully define some local variable and use like this, why would I need to assign it to self.
-(id) init
{
id tmp = [super init];
if(tmp != nil) {
//do stuff
}
return tmp;
}
b. If [super init] returns some other object instance and I have to overwrite self then I will not be able to access A’s methods any more, since it will be completely new object? Am I right?
c. super and self pointing to the same memory and the major difference between them is method lookup order. Am I right?
sorry, don’t have Mac to try, learning theory as for now…
Dreamlax’s answer is correct… but, clarification may be helpful.
selfis not a local variable. It is an argument to the method call. The first argument, in fact. The second argument is_cmd, the name of the selector of the method being executed.What is special about
selfis thatselfis used by the compiler to access instance variables. That is, if you sayself = [super init]and the superclass’sinithappens to return something different, any further instance variable accesses will still be correct.If super’s
initreturns an instance of something that is incompatible withA, then something has gone horribly awry in the design of the superclass. Keep in mind that Objective-C is fully dynamic. Thus, there is no reason that whatever is returned by super’sinitactually needs to be an instance ofA, but it better had damned well act like anA. Now, it could be a completely new instance of a subclass ofAand, thus, all of the methods ofAwill work just fine.Reading between the lines; remember that Objective-C is fully dynamic. There is no such thing as static method dispatch. The class of an object could change at any time and any random method call will still work as long as the new class responds to the method. Not that this actually happens at runtime, just that it could.
Now, this is the fun question.
superdoesn’t really point to anything. For all intents and purposes,supercan be treated as the one bit of magic in this. That is, when the compiler seessuperas the target of a method call, it compiles it as a slightly different call site that calls through to one of the variants ofobjc_msgSendSuper()which — as name implies — effectively “searches” for the method’s implementation starting in the parent class of the class within which the call was compiled.