Please help me making this clear about instance methods in Objective C:
- Can send messages to
selfandsuperinside- both dispatch the message to the calling object, but use different implementations
- if a superclass of yours calls a method on
self, it will [execute] your implementation (if one exists)
Okay, now that it’s actually possible to understand the question:
Let’s say you have a class
Foowith methodsdoSomethinganddoSomethingElse, and you make a subclass ofFoocalledBar.In your implementation of
Bar, if you wanted to calldoSomethingyou could either do[self doSomething]or[super doSomething].[super doSomething]would use the superclass’s implementation ofdoSomething—specifically,Foo‘s implementation.[self doSomething]would use the class itself’s implementation ofdoSomething—that is,Bar‘s implementation. Note that ifBardidn’t actually overridedoSomething, then[self doSomething]would end up calling the superclass’s implementation.As for what happens if a superclass calls a method on
self, let’s sayBaroverridesdoSomething, but doesn’t overridedoSomethingElse, and let’s saydoSomethingElselooks like this:What happens if you call
doSomethingElseonFoo *aFooandBar *aBar? The result of[aFoo doSomethingElse]is clear: it does[self doSomething]whereselfis aFoo, soFoo‘s implementation ofdoSomethingwill be executed.But when you do
[aBar doSomethingElse]is where things get interesting, and is what Paul was getting at. sinceBardoesn’t overridedoSomethingElse,Foo‘s implementation will be called, which in turn does[self doSomething]. But this time,selfis an instance ofBar, and soBar‘s implementation of doSomething will be called.Why would
[self doSomething]in the implementation ofFooend up executing code from the subclassBar? This is because of how messages are dispatched in Objective-C.[self doSomething]sends the messagedoSomethingto the objectself, and it is up to whatever objectselfis to decide what code gets executed. Sinceself, in this situation, would be aBar,Bar‘s implementation ofdoSomethingis executed.