Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]; 
like image 662
Sean Dunford Avatar asked Feb 15 '23 06:02

Sean Dunford


1 Answers

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.

like image 172
rmaddy Avatar answered Feb 22 '23 20:02

rmaddy