Does it make a difference where to put [super viewDidLoad] in my UIViewController? [duplicate]

早过忘川 提交于 2019-12-24 00:44:11

问题


Possible Duplicate:
[super viewDidLoad] convention

Does it make a difference where I put [super viewDidLoad] within the viewDidLoad in my UIViewController? I.e., should it go at the beginning (before my code to set up the UIViewController) or the end )after my code to set up the UIViewController) of the method, or does it not make any difference?


回答1:


You should usually call super as early as possible. Otherwise, the superclass may interfere with your own implementation. Let's say UIViewController would set a default background color in viewDidLoad (it doesn't): if you'd set your own background color in your method and then call super, it would be reset to the default color which could lead to confusion.




回答2:


Yes absolutely.

//superclass
-(void)viewDidLoad {
    self.ivar = 4;
}

//subclass
-(void)viewDidLoad {
    [super viewDidLoad];
    self.ivar = 5;
}

//alternative subclass
-(void)viewDidLoad {
    self.ivar = 5;
    [super viewDidLoad];
}

The example is trivial but shows two subclass both inheriting from the same superclass; one of which sets it's ivar to 4 after loading and the other sets it's ivar to 5.

I try to stick to what idz says above and always call a [super viewDidLoad] first; also do all your releasing in dealloc before calling [super dealloc] - i.e. get rid of all the mess first - otherwise it's leak time.




回答3:


You should put it at the beginning so that you can override anything it does (because lets face it that is why you are overriding in the first place). Or to look at it another way, you should not put it after any of your code in case it undoes anything you do. Hope this makes sense to you!




回答4:


The documentation actually doesn't indicate it's required, and several of Apple's sample code projects (e.g., iPhoneCoreDataRecipes) don't call [ super viewDidLoad ] at all. Compare this with the documentation of -viewWillAppear:, which explicitly says:

If you override this method, you must call super at some point in your implementation.

That said, it doesn't hurt to call it. My habit has been to call it immediately, then continue with my view setup.



来源:https://stackoverflow.com/questions/6033668/does-it-make-a-difference-where-to-put-super-viewdidload-in-my-uiviewcontrolle

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