The Keyword super
Sometimes (quite often, in Cocoa programming) you want to override an inherited method but still access the overridden functionality. To do so, you’ll use the keyword super. Like self, the keyword super is something you send a message to. But its meaning has nothing to do with “this instance” or any other instance. The keyword super is class-based, and it means: “Start the search for messages I receive in the superclass of this class” (where “this class” is the class where the keyword super appears).
You can do anything you like with super, but its primary purpose, as I’ve already said, is to access overridden functionality — typically from within the very functionality that does the overriding, so as to get both the overridden functionality and some additional functionality.
For example, suppose we define a class NoisyDog, a subclass of Dog. When told to bark, it barks twice:
@implementation NoisyDog : Dog
- (NSString*) bark {
return [NSString stringWithFormat: @"%@ %@", [super bark], [super bark]];
}
@endThat code calls super’s implementation of bark, twice; it assembles the two resulting strings into a single string with a space between, and returns that (using the stringWithFormat: method). Because Dog’s bark method returns @"Woof!", NoisyDog’s bark method returns @"Woof! Woof!". Notice that there is no circularity or recursion here: NoisyDog’s bark method will never call itself.
A nice feature of this architecture is that by sending a message to the keyword
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access