2

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?

ma11hew28
  • 121,420
  • 116
  • 450
  • 651

2 Answers2

7

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:.

Alex
  • 26,829
  • 3
  • 55
  • 74
  • 4
    What about `initWithCoder:`? According to the Documentation, that gets called when loading `UIView` subclasses from a nib file. Does `initWithFrame:` call `-initWithCoder:`? If so, then could I just implement `-initWithCoder:`? – ma11hew28 Jun 23 '11 at 15:58
2

Well awakeFromNib is called whenever all of the connections between the XIB and NIB are set. I believe awakeFromNib is called on an object when it is initialized from a nib file. So if you are creating it programmatically and not with a NIB file, then there's no need to call awakeFromNib. Calling initWithFrame, on the other hand, sounds like the way to go. In this function you can programmatically create your view, with no need for a nib file. I could be wrong, but I think initWithFrame is called regardless of whether your view is being created with a nib or not.

Mike C
  • 1,959
  • 2
  • 17
  • 17
  • 3
    `initWithFrame:` is called in AppKit on Mac OS, but not in UIKit on iOS, per the documentation here: http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/LoadingResources/CocoaNibs/CocoaNibs.html#//apple_ref/doc/uid/10000051i-CH4-SW18 – Alex Jun 22 '11 at 21:14