`[super viewDidLoad]` convention

IphoneObjective CCocoaCocoa Touch

Iphone Problem Overview


I see some example code with [super viewDidLoad] called before your implementation and after your implementation.

I know you don't always have to call super (as seen in many other discussions). When you do call it, is it expected before or after you code?

This could have consequences depending on what super's implementation does. Though you shouldn't have to know super's implementation to write yours.

Of course this goes for all of UIViewControllers delegate methods (willAppear, didAppear, etc...)

Any thoughts?

Iphone Solutions


Solution 1 - Iphone

My rule of thumb is: if you're doing something related to initialization, always call the super class's method first (if you are going to call it at all). This gives the super class a chance to do any set-up that you may be relying on later in your method. If you're doing something related to destruction, call the super class's method last. This makes sure that you can rely on the state of the object throughout the execution of your method. Finally, take any other case on a case-by-case basis. For instance, if you're handling an event, you probably want to deal with the event first, and only invoke the super class's method if you chose not to handle the event or if you somehow altered it and want to pass it along the event chain.

Solution 2 - Iphone

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCorey FloydView Question on Stackoverflow
Solution 1 - IphoneJason CocoView Answer on Stackoverflow
Solution 2 - IphoneKishore SutharView Answer on Stackoverflow