Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone UIViewController init method not being called

Tags:

iphone

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.

like image 971
farhany Avatar asked Apr 21 '09 11:04

farhany


4 Answers

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.

like image 112
reinaldoluckman Avatar answered Nov 16 '22 04:11

reinaldoluckman


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.

like image 34
Pablo Santa Cruz Avatar answered Nov 16 '22 04:11

Pablo Santa Cruz


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];
    //..
}
like image 24
Sean Avatar answered Nov 16 '22 03:11

Sean


Refer 'designated initializer' in reference document too.

like image 40
eonil Avatar answered Nov 16 '22 04:11

eonil