When programming iOS ViewControllers should you call parent class methods before or after your own code?

£可爱£侵袭症+ 提交于 2020-01-05 04:31:06

问题


A new iOS ViewControllers created 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?
}

回答1:


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.




回答2:


In viewDidLoad (and generally) you should go after, cause its calling the load method on the parent class

In dealloc you'd go before



来源:https://stackoverflow.com/questions/3797557/when-programming-ios-viewcontrollers-should-you-call-parent-class-methods-before

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!