Reputation: 1521
I am very new to iPhone programming and am running into a little bit of weirdness. For the following class, the init method just never gets called -- I have an NSLog function which should tell me when init is executed. Here's the relevant code:
@interface MyViewController : UIViewController {
}
@end
@implementation MyViewController
- (id) init
{
NSLog(@"init invoked");
return self;
}
@end
Any ideas as to what I am doing wrong -- if anything? Hopefully I provided enough information.
Thanks.
Upvotes: 11
Views: 18068
Reputation: 6348
If you are using a Storyboard, initWithCoder:
will be called. Reference document says:
If your app uses a storyboard to define a view controller and its associated views, your app never initializes objects of that class directly. Instead, view controllers are either instantiated by the storyboard—either automatically by iOS when a segue is triggered or programmatically when your app calls the storyboard object’s instantiateViewControllerWithIdentifier: method. When instantiating a view controller from a storyboard, iOS initializes the new view controller by calling its initWithCoder: method instead. iOS automatically sets the nibName property to a nib file stored inside the storyboard.
The initWithCoder:
method isn't part of the default template of a .m file, so you have to add yourself in your UIViewController subclass:
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
// Custom initialization
NSLog(@"Was called...");
}
return self;
}
There is no need to delete initWithNibName:bundle:
from your code, but it won't be called anyway.
Upvotes: 28
Reputation: 89
But, a UI component has sometimes severals init* methods, do we need to override all these methods in order to do some init. stuff?
Upvotes: 1
Reputation: 181290
You are probably creating your view controller from a NIB file. So, instead of calling "init" message, this is the one creator message being called:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}
Try if that is the one being called. What Sean said is true. You could use those messages to accomplish similar things.
Good luck.
Upvotes: 23
Reputation: 2463
Is the view coming up? Use these methods for additional initialization:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
//...
}
// Implement viewDidLoad to do additional setup after loading the view.
- (void)viewDidLoad {
[super viewDidLoad];
//..
}
Upvotes: 3