just had a noob question. I’m trying to understand the difference between calling self and super. Now I understand inheritance and other fundamental OOP concepts, but the idea of self and super is still not clear to me. I’ll illustrate my question with an example.
So the the below code performs a segue when the phone is tilted upside-down. I understand that “Scene2ViewController” is a subclass of “UIViewController” and so “Scene2ViewController” inherits all of UIViewController’s methods. And so below I’m calling the method performSegueWithIdentifier with the receiver of the message being self. Now when I change “self” to “super” the code still executes the same way. Isn’t calling super the same as calling self? If someone could explain this to me it would be appreciated, thanks.
//Scene2ViewController.m
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
if (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
[self performSegueWithIdentifier:@"SegueToScene1" sender:self];
}
return (interfaceOrientation ==
UIInterfaceOrientationPortrait);
}
selfandsuperactually both point to the same object.superis a keyword that tells the compiler to generate instructions that start the search for a method definition in the super class rather than in the current class.If we assume, per the comment, that the last lines are somewhere in a method of B, then
selfpoints to some instance of B.superalso points to that same instance of B. But when you useselfto callfoo, the search for an implementation offoostarts with class B. When you usesuper, the search for afoostarts with B’s superclass, A.superis especially handy when you want to preserve the inherited behavior, but add something on. So, we could have B’s implementation offoocall A’s version using[super foo]. Withoutsuperthere’d be no way to call the inherited method, and callingfoofrom the overridden method would result in infinite recursion.