What does [super viewWillAppear] do, and when is it required?
-(void)viewWillAppear开发者_C百科:(BOOL)animated{
//something here
[super viewWillAppear];
}
Is [super viewWillAppear];
always required? If not when and why do you use it?
First of all, the correct boiler plate should be:
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
//something here
}
In other words, call super
first, then do your own thing. And you have to pass the animated
parameter to super
.
You usually want to call the super class' implementation first in any method. In many languages it's required. In Objective-C it's not, but you can easily run into trouble if you don't put it at the top of your method. (That said, I sometimes break this pattern.)
Is calling super's
implementation required? In the case of this particular method you could get unexpected behavior if you don't call it (especially if you have subclassed a UINavigationController
for example). So the answer is no not in a technical sense, but you should probably always do it.
However, in many other methods there may be good reasons for not calling super
.
Calling super
method provide possibility to execute code in parent class.
Regarding your question according to Apple doc
So, yes, this method required.
In my experience, calling [super viewWillAppear]
in the first line, when calling reloadData
after that, makes it impossible to retrieve the previously selected row when coming back from a detail view. When [super viewWillAppear]
is the last sentence, you can get the selected row and show the previously selected row hint. This happens only when using [tableView reloadData]
inside viewWillAppear
.
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.
精彩评论