在Objective C中级联构造函数是否安全?

时间:2015-09-14 22:07:29

标签: objective-c multiple-constructors

我想做以下事情:

// I want to do this! :D

- (instancetype) init
{
    return [self initWithVal1:[NSDecimalNumber zero] val2:MyEnumDefault];
}

- (instancetype) initWithVal1:(NSDecimalNumber*)val1 val2:(MyEnum)val2
{
    return [self initWithVal1:val1 val2:val2 val3:12];
}

- (instancetype) initWithVal1:(NSDecimalNumber*)val1 val2:(MyEnum)val2 val3:(NSInteger)val3
{
    if (self = [super init])
    {
        _prop1 = val1;
        _prop2 = val2;
        _prop3 = val3;
    }
    return self;
}

但我知道,当我致电[self initWithVal1:[NSDecimalNumber zero]时,self尚未初始化。但是,我已经看到围绕itnernet的示例在示例中显示了这一点。 这样安全吗,或者我是否每次都要对它们进行初始化?

// I don't want to do this... :(

- (instancetype) init
{
    if (self = [super init])
    {
        _prop1 = [NSDecimalNumber zero];
        _prop2 = MyEnumDefault;
        _prop3 = 12;
    }
    return self;
}

- (instancetype) initWithVal1:(NSDecimalNumber*)val1 val2:(MyEnum)val2
{
    if (self = [super init])
    {
        _prop1 = val1;
        _prop2 = val2;
        _prop3 = 12;
    }
    return self;
}

- (instancetype) initWithVal1:(NSDecimalNumber*)val1 val2:(MyEnum)val2 val3:(NSInteger)val3
{
    if (self = [super init])
    {
        _prop1 = val1;
        _prop2 = val2;
        _prop3 = val3;
    }
    return self;
}

我不喜欢这种方法,因为它会复制代码,例如_prop3 = 12,如果必须稍后更改代码,则会导致潜在的差异。

1 个答案:

答案 0 :(得分:0)

安全,因为self在调用alloc时已经分配(init}。因此,可以在其上调用方法,但其对象只是尚未分配。