【问题标题】:Using @property on ARC在 ARC 上使用 @property
【发布时间】:2013-02-08 21:59:38
【问题描述】:
// .h
@property ( strong, nonatomic ) NSString *note;

// .m
@synthesize note = _note;

- ( id ) initWithNote: ( NSString * )note {

    self = [ super init ];
    if ( self ) {
        _note = note;   // _note is just a instance variable.
        self.note = note;   // 'self.note = note;' is using setter method.
        return self;
    }
    return nil;
}

@property ( strong, nonatomic ) NSString *note; 影响 setter 和 getter 方法。 并且默认情况下,ARC 上的变量是 __strong 类型。

那么_note = note;self.note = note; 有什么区别呢? 而不是strong,非ARC 上的retain 在这种情况下会有所作为。

【问题讨论】:

    标签: iphone ios properties automatic-ref-counting


    【解决方案1】:

    如果我正确理解了这个问题...

    如果您要覆盖 setter,您希望分配给 _propertyName 而不是 self.propertyName,以避免无限递归:

    - (void)setNote:(NSString *)note
    {
        _note = note;
        // self.note = note; // <-- doing this instead would freeze, and possibly crash your app
    }
    

    如果您要覆盖 getter,也是如此。在其他情况下,您可以使用两者中的任何一种。

    【讨论】:

    • 实际上self.note = note 不会使应用程序崩溃 - 它会将其冻结成一个 setter 调用自身的无限循环。
    • 你是对的,它首先对递归调用变得无响应。它也可能在堆栈内存空间用完后最终崩溃。感谢您的更正,我会更新答案。
    • @rokjarc,不,在 setter 中执行此操作将导致您的应用程序由于 堆栈溢出而崩溃(足够恰当。)我已经不小心做了几次,并且可以肯定地说它会崩溃。不到一分钟。
    • @DuncanC:你说的是二传手内部的self.note = note?是的 - 最终它会崩溃,你是对的。
    【解决方案2】:

    如果您使用(nonatomic),它们现在实际上是相同的。但是,如果您使用 (atomic)(默认设置)或者更有可能定义自定义设置器,它们会有所不同:

    - (void)setNote:(NSString *)note {
        // Do something fancier than this
        _note = note;
    }
    self.note = note; // use the custom setter
    

    _note = note; // set the variable directly
    

    【讨论】:

      猜你喜欢
      • 2012-04-19
      • 2012-03-09
      • 1970-01-01
      • 2012-09-20
      • 2012-02-01
      • 2011-12-09
      • 2018-05-05
      相关资源
      最近更新 更多