10

In order to initialize a view that has xib, I use initWithCoder function. But what if I need to initialize the xib with custom parameter.

I need something like this:

- (id)initWithCoder:(NSCoder *)aDecoder
           andTitle:(NSString *)titleString
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.titleLabel = titleString;
    }
    return self;
}

And when do I call it? After awakeFromNib?

2 Answers 2

11

You can't modify the initWithCoder: method like that because the method is defined in a protocol you don't control. Instead you need to either call the setTitle: method after the object has been created, possibly in awakeFromNib, or from the owning controller.

Sign up to request clarification or add additional context in comments.

2 Comments

you would not set the custom field in awakeFromNib
@SÄN why would you not set the text of a label in awakeFromNib ?
9

You don't call initWithCoder yourself, usually, so you can't pass custom parameters to it. That method would be called by the nib loading mechanism and you don't have control over it.

You certainly wouldn't call it from awakeFromNib - the object would already have been initialised by that point so you couldn't re-call it.

The simplest solution is to expose your custom parameters as properties and just set them after you've created the view.

2 Comments

Agreed, I sure wish I could create a custom init method to pass along parameters so it happens all in one go.
What about Swift ... if i want to pass my custom properties in initwithcoder method which i would like to declare as let .... how can i do that ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.