Does it make a difference where to put [super view

2019-07-21 10:50发布

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?

4条回答
Deceive 欺骗
2楼-- · 2019-07-21 11:28

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.

查看更多
Explosion°爆炸
3楼-- · 2019-07-21 11:30

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楼-- · 2019-07-21 11:36

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.

查看更多
闹够了就滚
5楼-- · 2019-07-21 11:37

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.

查看更多
登录 后发表回答