What are the side effects of calling [super loadVi

2019-05-06 19:11发布

问题:

In the docs for loadView, Apple states:

Your custom implementation of this method should not call super.

So I tried calling [super loadView] in my loadView method. Nothing bad seemed to happen and there was no warning. I'm using a view created programatically, in loadView, not from a NIB.

What (if any) bad things actually happen when I call [super loadView]?

回答1:

Calling [super loadView] will cause the UIViewController implementation of loadView to run. Among other things, this is the method that loads a view from a NIB, if a nibName has been provided. So if you were to call super last, it might overwrite all the view setup you did in your own subclass. If you call super first, this wouldn't be a problem... unless you have any code in -awakeFromNib or something.

Basically, you shouldn't call super because if you're loading your view programmatically, none of the work done in the superclass is work you want to keep. At best, you're throwing away a bunch of work. At worst, UIViewController may set up some state in there that makes assumptions about the origin of the view.

You don't need it, so don't do it.



回答2:

If you allow me this comparison, it's like "Don't cross the street on red."

There is a traffic light that establishes a rule not to cross the street because it might be dangerous whatever the reasons. It is perfectly plausible that you might cross the street on red and nothing happens.

The API sets up the is rule by stating you should not call super. Like in the example above, the outcome is undetermined and depends on other things. It is perfectly plausible that nothing happens.