3

I want to implement a custom initialization method for my UIViewController subclass to "replace" the initWithNibName method.

This is the code:

- (id) initWithMessage:(NSString *)message {
    if ((self = [super initWithNibName:@"ToolTip" bundle:nil])) {
        label.text = message;
    }

    return self;
}

The label is loaded from xib but at this point the reference to the label is nil (probably because the xib is not loaded yet?). Does anyone know a solution for that? Thanks

2 Answers 2

13

I know this is an old question, but the correct answer is to use the viewDidLoad method to do any additional setup after the view has loaded. The view is not loaded until it's needed, and may be unloaded when a memory warning is received. For that reason, a view controller's view should not be touched in an init method.

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

Comments

2

You should declare the label programmatically and initialize it within the init rather than do it from the nib.

This is how :

Assume UILabel *label is a class variable with @property and @synthesize defined for it.

- (id) initWithMessage:(NSString *)message {

    if ((self = [super initWithNibName:@"ToolTip" bundle:nil])) {
        label = [[UILabel alloc] init];
        label.text = message;
        [self.view addSubView:label];
    }

    return self;
}

Release the label in the "dealloc" method. Hope this helps.

Comments

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.