4

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]; 
4

1 回答 1

8

UIView init来电UIView initWithFrame:。由于您覆盖了两者,因此调用您的init方法会导致您的initWithFrame:方法被调用:

换句话说:你的init电话UIView initUIView init来电initWithFrame:。由于您覆盖initWithFrame:,您的initWithFrame:被调用,而后者又调用UIView initWithFrame:.

由于initWithFrame:总是会调用您的解决方案,因此解决方案是foo从您的init方法中删除对的调用。

于 2013-09-16T23:27:08.190 回答