【问题标题】:Objective-C: Why not call the designated initializer?Objective-C:为什么不调用指定的初始化器?
【发布时间】:2015-02-26 10:39:59
【问题描述】:

我继承了这段代码:

- (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;
}

【问题讨论】:

    标签: objective-c designated-initializer


    【解决方案1】:

    - (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;
    

    【讨论】:

    • 鉴于答案都差不多,我选择了这个,因为它提到了 NS_DESIGNATED_INITIALIZER。
    【解决方案2】:

    更合适的方式是这样的:

    - (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;
    }
    

    【讨论】:

      【解决方案3】:

      你真正需要做的就是……

      - (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;
      }
      

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

      【讨论】:

        猜你喜欢
        • 2019-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-23
        相关资源
        最近更新 更多