2012-03-21 105 views
-3

可能重複:
What exactly does @synthesize do?
Can someone explain this @synthesize syntax?@synthesize羽毛= _feathers?

@interface Duck : NSObject { 

    NSArray *_feathers; 

} 
@property (nonatomic,retain) NSArray *feathers; 

@end 

@implementation Duck 

@synthesize feathers=_feathers; 

@end 

我想知道究竟是什麼,當你做@synthesize羽毛= _feathers要去?

+1

你應該看看這個問題http://stackoverflow.com/questions/822487/how-在可變目標-c-class-work前面加一個下劃線 – Sakares 2012-03-21 08:23:48

+1

開始閱讀[Objective-C](https://developer.apple.com/library /ios/#documentation/Cocoa/Conceptual/ObjectiveC/Introduction/introObjectiveC.html)文檔。特別是關於[屬性]的部分(https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html#//apple_ref/doc/uid/TP40008048-CH101- SW1) – rckoenes 2012-03-21 08:24:46

+0

除了Apple的文檔,有些搜索可以幫助你 - 即使在這個網站。就在昨天,我回答了同樣的問題:http://stackoverflow.com/questions/9771434/iphone-instance-variable-issue/9771696#9771696 – MrTJ 2012-03-21 08:34:40

回答

1

你的情況(因爲你的財產是非原子)

@synthesize feathers=_feathers; 

等於

- (void)setFeathers:(NSArray *)newFeathers 
{ 
    if (newFeathers != _feathers) 
    { 
     [_feathers release]; 
     _feathers = [newFeathers retain]; 
    } 
} 

- (NSArray *)feathers 
{ 
    return feathers_; 
} 
+2

不完全 - 你也必須檢查看看'_fathers!=父親'在在第一次釋放時,setter會錯誤地釋放父對象。 (處理這個問題的另一種方法是'autorelease'而不是'release') – deanWombourne 2012-03-21 08:36:45

+1

@deanWombourne或者在釋放舊的值之前保留新值,這樣如果它是相同的對象,retainCount不會下降到0 。 – 2013-03-11 00:32:08

+0

@ SlippD.Thompson這就是我的意思:) - 你的解釋雖然更好! – deanWombourne 2013-03-11 19:29:17