美文网首页
NS_DESIGNATED_INITIALIZER 和初始化

NS_DESIGNATED_INITIALIZER 和初始化

作者: 梓华 | 来源:发表于2019-07-05 14:22 被阅读0次

参考
http://www.saitjr.com/ios/ios-ns_unavailable-ns_designated_initializer.html
https://www.jianshu.com/p/5654942cd8f7

@implementation CustomView

- (instancetype)init
{
    if(self = [super init])
    {
        [self createUI];
    }
    
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        [self createUI];
    }
    
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if(self = [super initWithCoder:aDecoder])
    {
        [self createUI];
    }
    
    return self;
}
会调用2次createUI
- (void)test_custom_view_1
{
    CustomView *customView = [[CustomView alloc] init];
    customView.frame = CGRectMake(100, 100, 200, 200);
    customView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:customView];
}
会调用1次createUI
- (void)test_custom_view_2
{
    CustomView *customView = [[CustomView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
    customView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:customView];
}

UIView的初始化方法列表

  • (instancetype)initWithFrame:(CGRect)frame NS_DESIGNATED_INITIALIZER;
  • (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;

当有多个初始化方法时 为了确保能够正确初始化 最终都会调用designed initializer

相关文章

网友评论

      本文标题:NS_DESIGNATED_INITIALIZER 和初始化

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