I created a new Xcode project with a view-based app template. In the .m of the view controller I overwrote this:
// The designated initializer. Override to perform setup 开发者_JAVA百科that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Custom initialization
NSLog(@"initWithNibName...");
}
return self;
}
- (id)init {
NSLog(@"initWithNibName...");
return [super init];
}
However, I never get that NSLog. That's also my experience from other projects. This method is never called. Not even -init from NSObject.
The View Controller is created inside the XIB file. How's that possible, that the Nib Loading System instantiates this class without any kind of initialization?
Why? And what's the alternative instead of -loadView and -viewDidLoad?
Another great reason to stay far away from XIB files?
From the iOS Resource Programming Guide
In iPhone OS, any object that conforms to the NSCoding protocol is initialized using the
initWithCoder:
method. This includes all subclasses ofUIView
andUIViewController
whether they are part of the default Interface Builder library or custom classes you define.
Think of it this way: the designated initializer is called when your view controller is first created in Interface Builder. Then, when you save the nib file, the view controller instance is stored in the file. Later, when the nib is loaded, the instance is recreated from the nib.
Since it's being recreated rather than created for the first time, a different initialization method is used. This method (-initWithCoder:
) restores the object's state using values from the nib file, which can include settings for properties beyond those that were set by the designated initializer. This mechanism relies on the NSCoding
protocol, which allows it to work generically for many different classes.
You can use - awakeFromNib for this. The init is only called if you do so in code.
Have you set your MainWindow's delegate as your appDelegate..?
Implement UIApplicationDelegate
in your AppDelegate and in the applicationDidFinishLaunching
Methode,try initWithNibName
.
That will do the trick.
精彩评论