Question

I have created a new project in xcode 4.5 and I have called my viewcontroller by

-(id)initWithNibName:bundle:

from appdelegate as it called in default project template and i am not using storyboard but awakeFromNib was not called I have also searched but not able to understand why awakeFromNib is not calling.

By apple documentation for -(void)awakeFromNib "Prepares the receiver for service after it has been loaded from an Interface Builder archive, or nib file." "Objects that conform to the NSCoding protocol (including all subclasses of UIView and UIViewController) are initialized using their initWithCoder: method. All objects that do not conform to the NSCoding protocol are initialized using their init method. After all objects have been instantiated and initialized, the nib-loading code reestablishes the outlet and action connections for all of those objects. It then calls the awakeFromNib method of the objects."

My question is that Why awakeFromNib is not calling when xib file is loaded? Is i am doing something wrong?Please elaborate

Was it helpful?

Solution

awakeFromNib: is called only if the view controller is inside the nib file.
In this case you init the view controller with init initWithNibName:bundle, so the content of the view controller is inside the nib, not the view controller itself.
If you open the xib file, drag an object inside the xib and set the class to be your view controller class name, then awakeFromNib will be called (this case you don't need to initialize manually the view controller).
So keep in mind the difference between having a view controller in a xib file, and having a view controller not in a xib file, but with all it's contents loaded from a xib file.

PS: I used nib and xib interchangeably.

EDIT
I forgot to tell you how to go around this.Override viewDidLoad to do things with the initialized outlets.

OTHER TIPS

Why not just add the -(id)initWithNibName:bundle: method to your subclass instead of -(void)awakeFromNib?

My "awakeFromNib" methods are called just fine but I load my view controller with:

myViewController *vc = [[[NSBundle mainBundle] loadNibNamed:@"myViewController" owner:self options:nil] objectAtIndex:0];

so I'm wondering if your awakeFromNib isn't called because you're using initWithNibName instead?

EDIT: I just saw your comment that you're adding the awakeFromNib to the ViewController of the default project that is created by XCode. Did you uncheck the "use StoryBoard" box when you created your project? If your nib is inside of the project's main storyboard, there may be some extra hoops you have to jump through.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top