Dreamlax's answer is correct... but, clarification may be helpful.
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.
self
is 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 self
is that self
is used by the compiler to access instance variables. That is, if you say self = [super init]
and the superclass's init
happens to return something different, any further instance variable accesses will still be correct.
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?
If super's init
returns an instance of something that is incompatible with A
, 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's init
actually needs to be an instance of A
, but it better had damned well act like an A
. Now, it could be a completely new instance of a subclass of A
and, thus, all of the methods of A
will 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.
c. super and self pointing to the same
memory and the major difference
between them is method lookup order.
Am I right?
Now, this is the fun question. super
doesn't really point to anything. For all intents and purposes, super
can be treated as the one bit of magic in this. That is, when the compiler sees super
as the target of a method call, it compiles it as a slightly different call site that calls through to one of the variants of objc_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.