Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

iphone - Description of initWithNibName, awakeFromNib and viewDidLoad?

Is there a good overview of initWithNibName, awakeFromNib, and viewDidLoad that lays out the best way to use each of these and describes exactly what each does? I find these very confusing. In the template that's generated with a View Controller, the comment about initWithNibName says:

The designated initializer. Override to perform setup that is required before the view is loaded.

Except that this method never seems to be called (I'm using IB to set up the View Controller). So should I use awakeFromNib or viewDidLoad to initialize instead?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I just finished doing some research on this topic so I thought I'd share a few of the things I learned.

  1. There's nothing wrong with using awakeFromNib with views for the iPhone. See this Apple Dev document.

  2. initWithCoder is not a good place to do initialization when the view is loaded from a NIB file because other items in the same NIB file may or may not have been initialized at that point. So an outlet might still be nil, for example. All items in the same NIB file are guaranteed to be initialized properly when awakeFromNib is called.

  3. viewDidLoad is a good place to do setup work in the viewController.

So why would one want to use awakeFromNib in the view? One reason I can think of is if you have stuff you want to do after the view has been initialized and hooked up to the other objects in the NIB file, but you want to encapsulate it in the view only. This reduces linkage with the view controller.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...