Search code examples
iosuikitnibawakefromnib

UIKit: call awakeFromNib programmatically?


I saw this code:

CoolButton *coolButton = [[CoolButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 60.0f, 25.0f)];
[coolButton awakeFromNib];
// ...
[coolButton release];

CoolButton subclasses UIButton. Is it OK to call awakeFromNib programmatically?

What's the best way to do this if I want to do the same things that are done in -[CoolButton awakeFromNib] for times that I want to create the object programmatically, instead of from a nib file?

Should I just define a method and call it in -[CoolButton awakeFromNib] and -[CoolButton initWithFrame]? Or, is there another initialization method I should define that gets called in both cases: whether I create a CoolButton programmatically or from a nib file?


Solution

  • No, there isn't a method that gets called both for objects created in code and objects created from a NIB. You should write a separate method that contains the common initialization logic and call it from both awakeFromNib and initWithFrame:.