开发者

ViewController init?

开发者 https://www.devze.com 2022-12-24 14:50 出处:网络
I have just noticed that my ViewController does not call init (See below) when it starts up. -(id)init {

I have just noticed that my ViewController does not call init (See below) when it starts up.

-(id)init {
    self = [super init];
    if(self) 开发者_如何学C{
        NSLog(@"_init: %@", [self class]);
        otherStuff...
    }
    return self;
}

Is there a reason for this, or is it replaced by viewDidLoad

-(void)viewDidLoad {
    otherStuff ..
    [super viewDidLoad];
}

cheers gary


It's not replaced by viewDidLoad. It's just that init's not called by initWithNibName:bundle:.

I just write my setup code in viewDidLoad.


If your view controller is being initialized from a storyboard, then you can use:

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        // do init here
    }
    return self;
}


awakeFromNib is commonly used.


  • (void) init works fine if you create the object in code, but you DO have to make sure it's the one you call. It doesn't do any good to flesh out the templated initWithNibName:bundle: method and then call the other one.
0

精彩评论

暂无评论...
验证码 换一张
取 消