如果我有一个像这样设置的类来自定义 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];
最佳答案
UIView init
调用 UIView initWithFrame:
。由于您覆盖了两者,因此调用 init
方法会导致调用 initWithFrame:
方法:
换句话说:您的 init
调用 UIView init
。 UIView init
调用 initWithFrame:
。由于您重写了 initWithFrame:
,您的 initWithFrame:
被调用,它又调用了 UIView initWithFrame:
。
由于您的 initWithFrame:
将始终被调用,因此解决方案是从您的 init
方法中删除对 foo
的调用。
关于ios - 为什么两个初始化函数都被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18838928/