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]]; } @end
That 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
Get Programming iOS 4 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.