When programming iOS ViewControllers should you call parent class methods before or after your own code?
A new iOS ViewControllers created开发者_JAVA百科 from a template contains several "boilerplate" methods that call their parent class methods.
-(void) viewDidLoad {
[super viewDidLoad];
}
- (void) viewDidUnload {
[super viewDidUnload];
}
- (void) dealloc {
[super dealloc];
}
When modify these classes, should I put my own code before or after the parent class calls?
- (void) viewDidLoad {
// Should I put my code here?
[super viewDidLoad];
// Or here?
}
This is applicable for all OOP in general. In constructor (and in other methods too) you should call the parent's constructor before your code. The reason is your code may require some initialization which are handled in parent, i.e. initialization of base should go before initialization of derived class. In destructor you should do the opposite, i.e. releasing of derived class's resources should go before releasing resources of base. The reason is straight forward. Derived class's resource may depend on base's resource. If you release resource of base before then there might be trouble.
This is the ideal case. In many cases you may see no difference but if there is dependency like described above then you will be in trouble. So you should follow the standard, call base class's method before your code and in dealloc do the opposite.
In viewDidLoad (and generally) you should go after, cause its calling the load method on the parent class
In dealloc you'd go before
精彩评论