views:

62

answers:

1

How should I write an init method for a class which is sub-classing an NSObject

  • Let's say i have a class named : CustomButton subclassing UIButton
  • I have an empty nib file named CustomButton.nib which has a single UIButton in it.
  • IN interface builder the classname for the button is set to "CustomButton"

How would you write an init method for this class so that it loads from the nib file?

+2  A: 

If you need custom initialization inside CustomButton, use this:

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super initWithCoder:decoder]) {
        /* do initialization here */
    }
return self;
}

This will not be called if you instantiate the button directly in code, only when instantiated bu the nib loader. Instantiating through code means you need to use initWithFrame so override that one. You may actually want to have initWithCoder and initWithFrame call the same initAlways method or something.

Also, it's important to know the Objective-C concept of "designated initializer" (look it up in objective C docs) because it can be a little confusing to people used to other OO languages.

Nimrod
PLEASE provide the way you instantiate the object using this init method. the init method requires an NSCoder, 1- what is this nscorer? 2- How do i create it? 3- Do i call this method directly?
aryaxt
You don't instantiate it yourself. The nib file is basically a serialized set of objects loaded by the nib loader, so the nib loader handles all the NSCoder stuff for you. You just have to make sure to do that [super ...] call in there. Basically overriding initWithCoder like this just inserts your code into the object instantiation that the nib loader does. Hope that makes sense....
Nimrod
Actually, you probably want to use awakeFromNib: instead. I forgot about that, duh. see http://stackoverflow.com/questions/2663333/what-method-of-uiview-gets-called-when-instantiated-from-a-nib
Nimrod
this doesn't work, initWithCoder never gets called
aryaxt