the Benifits of awakeFromNib?

2019-03-20 03:33发布

问题:

I've been learning coredata by making a lot of simple test apps based on the xcode Navigation controller template with "use coredata" checked.

The awakeFromNib method in the App delegate has been a source of problems for me, because I'm adding other views to the controller and changing the load sequence, so that RootViewController may be a second or third choice.

I've figured out what awakeFromNib is doing, and I've removed it so the app delegate is no longer tied to any particular view. (So when I do want to load RootViewController, I'll load it as a regular view, and use its own viewDidLoad to initialize the managedObjectContext for the view).

My question: are there performance gains or other benefits by using awakeFromNIb in the AppDelegate? or is it just another way of doing the same thing as I'm doing from the viewDidLoad method?

回答1:

All the methods fire at different times and different circumstances.

awakeFromNib is called when the nib file associated with a class is loaded from disk. Any class that can own a nib can use it. viewDidLoad is used only by view controllers. It is usually called when loading from nib as well but it can also be called by a view created in memory (very rare circumstance.)

In either case, you only put functionality in either that you only want to run once when the instance is first loaded. E.g. a common nubie mistake is to put code in viewDidLoad that needs to run every time the view appears. Say as with master view that opens a detail view and then reappears when the detail view is dismissed. If the code for the master view is in viewDidLoad it will only run the first time the master view is loaded but not any of the subsequent times the master view disappears and reappears.

You generally don't initialize any other views or do much of anything in the app delegate's awake from nib. That is usually performed in applicationDidFinishLaunching.