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.
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.
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.
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];
//..
}
Refer 'designated initializer' in reference document too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With