我想做以下事情:
// 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
,如果以后必须更改代码,这会导致潜在的差异。