Designated initializer : 特定构造方法(方法声明后面带有NS_DESIGNATED_INITIALIZER)
注意:子类如果重写了父类的特定构造方法, 那么必须使用super调用父类的特定构造方法,
比如下面的系统构造方法重写时,如果没有调用super则会报错提示:
Designated initializer missing a 'super' call to a designated initializer of the super class
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
self.titleLabel.font= [UIFontsystemFontOfSize:16];
// 文字颜色
[selfsetTitleColor:[UIColordarkGrayColor] forState:UIControlStateNormal];
[selfsetTitleColor:[UIColorredColor] forState:UIControlStateSelected];
}
returnself;
}
如果不是构造方法,也想让子类重写时不要忘记调用super,则可以使用NS_REQUIRES_SUPER
@interface XMGTest : NSObject
//模仿系统方法
- (instancetype)initWithName:(NSString *)name NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithAge:(NSInteger)age NS_DESIGNATED_INITIALIZER;
//自己的方法,提示需要调用super
- (void)run NS_REQUIRES_SUPER;
@end