O'Reilly logo

Programming iOS 4 by Matt Neuburg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required