请问initWithFrame:触发init?

时间:2011-12-21 09:16:19

标签: objective-c xcode subclass init

我创建了UIImageView的子类,我想在调用initWithFrame或initWithImage或Init时添加一些内容...

-(id) init {
  [super init];
  NSLog(@"Init triggered.");
}

如果我拨打-initWithFrame:方法,上面的-init也会被触发吗?

1 个答案:

答案 0 :(得分:8)

每个班级应该有一个designated initialiser。如果UIImageView遵循此约定(它应该,但我尚未对其进行测试),那么您会发现调用-init将最终调用-initWithFrame:

如果你想确保你的init方法运行,你所要做的就是覆盖父类的指定初始化,如下所示:

-(id) initWithFrame:(CGRect)frame;
{
    if((self = [super initWithFrame:frame])){
        //do initialisation here
    }
    return self;
}

或者像这样:

//always override superclass's designated initialiser
-(id) initWithFrame:(CGRect)frame;
{
    return [self initWithSomethingElse];
}

-(id) initWithSomethingElse;
{
    //always call superclass's designated initializer
    if((self = [super initWithFrame:CGRectZero])){
        //do initialisation here
    }
    return self;
}