2013-02-23 70 views
0
// .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類型。在ARC上使用@property

_note = note;self.note = note;然後有什麼區別? 而不是strong,非ARC的retain在這種情況下有所不同。

回答

1

如果您使用(nonatomic),它們現在實際上是相同的。

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

_note = note; // set the variable directly 
1

如果我理解正確的問題...

如果你覆蓋了一個二傳手,你想分配給_propertyName,而不是self.propertyName,以避免無限遞歸:

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

同樣的事情如果你重寫了吸氣劑。在其他情況下,您可以使用其中任何一種。

+0

其實'self.note = note':但是,如果你使用(atomic)(默認設置),或者更可能的是,定義一個定製的setter他們將不同不會使應用程序崩潰 - 它將它凍結成調用自己的setter的無限循環。 – 2013-02-23 11:49:38

+2

你說得對,它首先從遞歸調用變得沒有響應。它可能會在堆棧內存空間耗盡後最終崩潰。感謝您的更正,我會更新答案。 – Macondo2Seattle 2013-02-23 17:51:40

+1

@rokjarc,不,在一個setter裏面這樣做會導致你的應用程序因爲一個**堆棧溢出而崩潰**(足夠恰當)。我多次意外地做了它,並且可以肯定地說它會崩潰。它需要不到一分鐘。 – 2014-04-01 02:04:06

相關問題