Ben*_* Lu 8 xcode subclass objective-c init
我创建了UIImageView的子类,每当我调用initWithFrame或initWithImage或Init时,我想添加一些东西.
-(id) init {
[super init];
NSLog(@"Init triggered.");
}
Run Code Online (Sandbox Code Playgroud)
如果我打电话给-initWithFrame:方法,-init上面也会被触发吗?
每个班级都应该有一个指定的初始化者.如果UIImageView遵循这个约定(它应该,但我还没有测试过),那么你会发现调用-init最终会调用-initWithFrame:.
如果要确保运行init方法,您所要做的就是覆盖父类的指定初始化,如下所示:
-(id) initWithFrame:(CGRect)frame;
{
if((self = [super initWithFrame:frame])){
//do initialisation here
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
或者像这样:
//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;
}
Run Code Online (Sandbox Code Playgroud)