为什么两个初始化函数都会被调用

4
如果我有一个类像这样设置来自定义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 
}

为什么当我使用 foo 时它会被调用两次?
myView *aView = [[myView alloc]init]]; 

或者
myView *aView = [[myView alloc]initWithFram:aFrame]; 
1个回答

8

UIView init 调用 UIView initWithFrame:。由于您重写了两者,因此调用您的 init 方法会导致调用您的 initWithFrame: 方法:

换句话说:您的 init 调用 UIView initUIView init 调用 initWithFrame:。由于您重写了 initWithFrame:,因此将调用您的 initWithFrame:,该方法又调用 UIView initWithFrame:

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


1
最好实现initWithFrame:而不是init。我认为init调用[self initWithFrame:CGRectZero] - Bryan Chen
2
@rmaddy,反过来。 -[UIView init] 将调用指定的初始化方法 -[UIView initWithFrame:]。 OP希望保留对 [myView foo] 的调用在initWithFrame:中,并从 init 中删除它。 可能要完全删除 [myView init] - Firoze Lafeer
1
@FirozeLafeer 和 xlc。我搞错了,我更新了答案。 - rmaddy
我选择这个作为答案。不过,你的解释可以更简单明了。感谢你一直关注评论并纠正答案。 - Sean Dunford

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接