What does the SUPER in a subclass?

Discussion in 'iPhone/iPad Programming' started by yrvaken2, Jan 7, 2009.

  1. macrumors newbie

    Joined:
    Sep 15, 2008
    #1
    If you create a UITableView Controller Subclass in Xcode, the viewDidLoad have the following code:

    Code:
    - (void)viewDidLoad {
        [super viewDidLoad];
    }
    
    what does this "super" mean, when do you use that?

    Thanks Anders
     
  2. macrumors regular

    Joined:
    Jun 23, 2006
    Location:
    Glasgow, UK
    #2
    It's sending a message to do the 'viewDidLoad' method in the superclass (ie UIView) as well as what you've written in that class (since writing a viewDidLoad method will over-ride what's in UIView).
     
  3. macrumors regular

    Joined:
    Mar 24, 2008
    #3
    Lets say you have 2 class, a Parent and a Child. Child inherits from Parent. They have a method called greet which returns a string.

    Here is what the parent method looks like:

    Code:
    -(NSString *)greet {
      return @"Hello";
    }
    We want the child to learn from his parents. So we use super to say greet how Mommy would greet, but with our own little additions too.

    Code:
    // Inherits from Parent
    -(NSString *)greet {
      NSString *parentGreeting = [super greet];
      return [parentGreeting stringByAppendingString:@", Mommy"]
    }
    So now Parent greets "Hello", and the Child greets "Hello, Mommy". Later on, if we change the parent's greet to return just "Hi", then both classes will be affected and you will have "Hi" and "Hi, Mommy".

    super is used to call a method as defined by a superclass. It is used to access methods that have been overriden by subclasses so that the class can wrap its own code around a method that it's parent class implements. It's very handy if you are doing any sort of inheritance at all.
     
  4. thread starter macrumors newbie

    Joined:
    Sep 15, 2008
    #4
    Thanks for a good explanation!
     
  5. Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #5
    If you don't understand the concept of superclasses and how they fit in, you may be best served stepping back and learning a bunch more about Object-Oriented Programming before you continue.
     

Share This Page