美文网首页程序员
特定构造方法--如何让子类重写某些方法时提醒调用super

特定构造方法--如何让子类重写某些方法时提醒调用super

作者: 苹果API搬运工 | 来源:发表于2016-04-11 09:47 被阅读400次
 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

相关文章

网友评论

    本文标题:特定构造方法--如何让子类重写某些方法时提醒调用super

    本文链接:https://www.haomeiwen.com/subject/kycilttx.html