Sean Dunford
Sean Dunford

Reputation: 949

Why do both init functions get called

If I have a class that is setup like this to customize a UIView.

@interface myView : UIView

- (id)init {
    self = [super init];
    if(self){
        [self foo];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self foo];
    }
    return self;
}


-(void) foo{
   //Build UIView here 
}

How come foo is called twice whether I use

myView *aView = [[myView alloc]init]]; 

or

myView *aView = [[myView alloc]initWithFram:aFrame]; 

Upvotes: 4

Views: 420

Answers (1)

rmaddy
rmaddy

Reputation: 318814

UIView init calls UIView initWithFrame:. Since you override both, calling your init method results in your initWithFrame: method being called:

In other words: your init calls UIView init. UIView init calls initWithFrame:. Since you override initWithFrame:, your initWithFrame: is called which in turn calls UIView initWithFrame:.

The solution, since your initWithFrame: will always be called, is to remove the call to foo from your init method.

Upvotes: 8

Related Questions