为什么两个init函数都被调用 [英] Why do both init functions get called
问题描述
如果我有一个像这样设置的类来自定义UIView。
@interface myView:UIView
- (id)init {
pre>
self = [super init];
if(self){
[self foo];
}
return self;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if(self){
//初始化代码
[self foo];
}
return self;
}
- (void)foo {
//在此处构建UIView
}
如果我使用
$ f
$ b* aView = [[myView alloc] init]];
或
myView * aView = [[myView alloc] initWithFram:aFrame];
解决方案
UIView init
callUIView initWithFrame:
。因为你覆盖了两个,调用init
方法会导致调用initWithFrame:
方法:
换句话说:你的
init
调用UIView init
。UIView init
呼叫initWithFrame:
。因为你重载initWithFrame:
,你的initWithFrame:
被调用,依次调用UIView initWithFrame: 。
解决方案,因为
initWithFrame:
从init
方法中删除对foo
的调用。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];
解决方案
UIView init
callsUIView initWithFrame:
. Since you override both, calling yourinit
method results in yourinitWithFrame:
method being called:In other words: your
init
callsUIView init
.UIView init
callsinitWithFrame:
. Since you overrideinitWithFrame:
, yourinitWithFrame:
is called which in turn callsUIView initWithFrame:
.The solution, since your
initWithFrame:
will always be called, is to remove the call tofoo
from yourinit
method.这篇关于为什么两个init函数都被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!