Where to initialize something ONCE in a UIViewController

I have a UIViewController subclass and I'm trying to figure out what to override such that I can run some initialization code only once per object instance.

The viewDidLoad method might seem like the obvious answer, but the problem is that viewDidLoad may run more than once if the controller resets the view due to a memory warning. The initWithNibName:bundle: , init , and initWithCoder: methods also seem like good choices, but which one to override? The awakeFromNib method is another consideration, but that doesn't seem to be executed in my view controller.

Is there a way to do this that I'm missing?


你可能仍然可以使用viewDidLoad,但内部使用一个静态布尔值来查看你是否已经在那里。

static BOOL didInitialize = NO;
if (didInitialize == YES)
    return;

didInitialize = YES;
/* initialize my stuff */

UIViewControllers's designated initializer, the method that all other initializers are supposed to call, is -initWithNibName:bundle: . If you want to initialize something when your view controller is created, override that method.

-viewDidLoad is meant for any setup that depends on the controller's views. As you point out, that method may run more than once because the views may be loaded more than once. -awakeFromNib won't help unless your view controller itself exists in a nib, and even then it only makes sense if the thing that you're initializing depends on other objects in that same nib.


What about +(void)initialize ? That's a class initializer that iOS calls for you, once, for the class, as I understand it.

链接地址: http://www.djcxy.com/p/58354.html

上一篇: addChildViewController实际上做了什么?

下一篇: 在UIViewController中什么地方初始化一些东西