UIVIewController custom init method
I want to implement a custom initialization method for my UIViewController subclass to "replace" the initWithNibName method.
This is the code:
开发者_StackOverflow中文版- (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
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.
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.
精彩评论