aryaxt
aryaxt

Reputation: 77596

iPhone - How should I write an init method?

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

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

Upvotes: 2

Views: 1590

Answers (1)

Nimrod
Nimrod

Reputation: 5133

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.

Upvotes: 7

Related Questions