Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make subclass refer to XIB of its superclass?

I got a BaseClass UIViewController class. It works well. BaseClass has BaseClass.xib

Then I created a subclass of that base class.

Turns out none of the outlets are connected.

I put

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    return self;
}

And yes there it goes. It's called. I am not sure what aDecoder is. I think it's a representation of the XIB of the childClass, which doesn't exist. I want super to be initialized with the xib of super.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

is never called.

In fact, I am quite confused that myself. When we have xib, it seems that -(id)initWithCoder:(NSCoder *)aDecoder is the one that's called. So I wonder what initWithNibName is for?

I tried

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithNibName:NSStringFromClass([super class]) bundle:nil];
    return self;
}
like image 598
user4951 Avatar asked Nov 19 '25 17:11

user4951


1 Answers

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle is the designated initializer for UIViewController. So in your inherited class,

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:@"BaseClass" bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

Whenever Apple marks an initializer as the designated initializer, the other initializers will just point to the designated initializer. You do not need to implement the other initializers.

NIB loading uses initWithCoder which is why you see it getting called when nibs are loaded.

like image 54
Fruity Geek Avatar answered Nov 22 '25 08:11

Fruity Geek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!