在Objective-C中,为了添加自定义初始化逻辑,是否需要覆盖子类的所有继承构造函数?
例如,对于一个具有自定义初始化逻辑的UIView
子类,以下方法是否正确?
@implementation CustomUIView
- (id)init {
self = [super init];
if (self) {
[self initHelper];
}
return self;
}
- (id)initWithFrame:(CGRect)theFrame {
self = [super initWithFrame:theFrame];
if (self) {
[self initHelper];
}
return self;
}
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (self) {
[self initHelper];
}
return self;
}
- (void) initHelper {
// Custom initialization
}
@end
initWithCoder:
方法,而不是initWithFrame:
方法。 - PascalinitWithFrame
的内容:"如果你使用 Interface Builder 设计界面,当你的视图对象从 nib 文件中加载时,不会调用此方法。" - pauloyainitWithCoder:
是特殊的,它是NSCoding
类别的一部分。在这种情况下,您可以放心地覆盖指定的初始化程序initWithFrame:
,加上initWithCoder:
。 - Pascal