2011-09-16 38 views
1

考慮下面的類DEF:@synthesize statment在做什麼?

@interface MyController : OtherController { 
    NSString *_ID; 
} 
@property(nonatomic,retain) NSString *ID; 
@end 

和下面的實現:

@implementation DRMControllerNDS 
@synthesize ID =_ID; 
@end 

什麼是@synthesize語句在這裏做什麼?具體爲什麼我們將_ID實例變量值設置爲ID屬性?在這一點上,_ID不是nil嗎?我已經看到這個構造使用了很多次,並且還沒有明白它的目的...

任何人都可以解釋這個嗎?

+0

這是一個區分直接訪問變量(_var)和通過合成訪問器(self.var)訪問的約定。 – Jano

+0

類似問題:[1](http://stackoverflow.com/questions/3802851/objective-c-synthesize-property-name-overriding),[2](http://stackoverflow.com/questions/3277209/can -someone-explain-this-synthesize-syntax),[3](http://stackoverflow.com/questions/6112283/question-about-synthesize/6112553),[4](http://stackoverflow.com/questions/3802851),[5](http://stackoverflow.com/questions/382051),[6](http://stackoverflow.com/questions/3266467),[7](http://stackoverflow.com/問題/ 5170631),[8](http://stackoverflow.com/questions/3277209),[9](http://stackoverflow.com/questions/719788) – Jano

+0

@Sabobin:每個數字都是一個鏈接。 –

回答

4

用簡單的英語,@synthesize行說:「爲屬性」ID「創建getter和setter方法,但不要使用名爲」ID「的實例變量(缺省值)來存儲該值,請使用而不是名爲「_ID」的實例變量。「

0

如果您試圖訪問instanceOfMyController._ID,則會出現錯誤,因爲._ID屬性不存在; @synthesize指令允許您使用點符號。

有關更多信息,請參閱this question

+0

'_ID'屬性仍然不存在;沒有這樣的財產被宣佈。該屬性是'ID',這個'@ synthesize'指令告訴編譯器使用'ID'屬性的存儲'_ID'實例變量。 –

+0

因此,您的目標是允許您使用點符號還是使用實例變量名稱,但出於某種原因使它們保持分離?目前尚不清楚。換句話說,我可以寫:instanceOfMyController.ID或_ID來訪問變量?或者我只限於一個或另一個? – Elisabeth

+0

哦,只是想到了一些東西:正在使用_ID來避開使用getters和setters?也就是說,如果我使用instanceOfMyController.ID,我使用setter/getter,但是如果我使用_ID,我不是? – Elisabeth