Objective-C:为什么不调用指定的初始化程序?

时间:2015-02-26 10:40:00

标签: objective-c designated-initializer

我继承了这段代码:

- (id)initWithLocation:(CLLocation *)inLocation {
    if (self = [super init])
    {
        _location = [inLocation copy];
    }
    return self;
}

- (id)initWithLocation:(CLLocation *)inLocation offsetValue:(NSNumber *)offset {
    if (self = [super init])
    {
        _location = [inLocation copy];
        _offset = [offset copy];
    }
    return self;
}

我想知道第一种方法没有调用指定的初始化程序(例如像Is it okay to call an init method in self, in an init method?这样)有充分的理由吗?

即。为什么不这样做:

- (id)initWithLocation:(CLLocation *)inLocation {
    if (self = [super init])
    {
        [self initWithLocation:inLocation offsetValue:nil];
    }
    return self;
}

- (id)initWithLocation:(CLLocation *)inLocation offsetValue:(NSNumber *)offset {
    if (self = [super init])
    {
        _location = [inLocation copy];
        _offset = [offset copy];
    }
    return self;
}

3 个答案:

答案 0 :(得分:2)

- (id)initWithLocation:(CLLocation *)inLocation offsetValue:(NSNumber *)offset方法应该是指定的初始值设定项,- (id)initWithLocation:(CLLocation *)inLocation应该像这样调用它:

- (id)initWithLocation:(CLLocation *)inLocation {
    return [self initWithLocation:inLocation offsetValue:nil];
}

使用NS_DESIGNATED_INITIALIZER在类接口中标记指定的初始值设定项也是一种很好的做法:

- (id)initWithLocation:(CLLocation *)inLocation offsetValue:(NSNumber *)offset NS_DESIGNATED_INITIALIZER;

答案 1 :(得分:0)

更恰当的方式是:

- (id)initWithLocation:(CLLocation *)inLocation {
    return [self initWithLocation:inLocation offsetValue:nil];
}

- (id)initWithLocation:(CLLocation *)inLocation offsetValue:(NSNumber *)offset {
    if (self = [super init]) {
        _location = [inLocation copy];
        _offset = [offset copy];
    }
    return self;
}

答案 2 :(得分:0)

你真正需要做的就是......

- (id)initWithLocation:(CLLocation *)inLocation {
    return [self initWithLocation:inLocation offsetValue:nil];
}

- (id)initWithLocation:(CLLocation *)inLocation offsetValue:(NSNumber *)offset {
    if (self = [super init])
    {
        _location = [inLocation copy];
        _offset = [offset copy];
    }
    return self;
}

你是对的。在这种情况下没有理由不这样做。