2011-06-11 40 views
4

可能重複:
Prefixing property names with an underscore in Objective C對象 - @synthesize

iPhone應用程序開發者初學者在這裏:

在.H

@property (nonatomic, retain) IBOutlet UILabel *detailDescriptionLabel; 

在.M

@synthesize detailDescriptionLabel = _detailDescriptionLabel; 

我已經習慣了看到

@synthesize detailDescriptionLabel; 

= _是扔我了,這是什麼做的?

+0

另請參見:[Cocoa Objective-C類中的變量前面的下劃線如何工作?](http://stackoverflow.com/questions/822487/how-does-an-underscore-in-front-of -a-variable-in-a-cocoa-objective-c-class-work)和[下屬性名前綴](http://stackoverflow.com/questions/5582448/underscore-prefix-on-property-name) – 2011-06-11 18:11:27

+0

iOS 5處於NDA之下;編輯爲不違反。 – bbum 2011-06-11 18:15:44

回答

6

每個屬性都由一個實例變量支持。該語言允許他們命名不同。通過執行@synthesize detailDescriptionLabel = _detailDescriptionLabel;,您基本上在說使用_detailDescriptionLabel作爲屬性detailDescriptionLabel的後臺實例變量。如果你只是做@synthesize detailDescriptionLabel;,它隱含地理解實例變量具有相同的名稱。

+2

請注意,用戶代碼不應使用前面的下劃線字符:http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingBasics.html#//apple_ref/doc/uid/20001281 -1002931-BBCFHEAB – 2011-06-11 18:10:50

+2

的確如此。但是,你看過由XCode 4的界面生成器生成的代碼嗎?大部分時間它都會增加下劃線。 – 2011-06-11 18:14:31

+0

明白了。謝謝。奇怪的是,新的Xcode用於保持名稱相同,但它的默認代碼更改實例變量的名稱 – user544359 2011-06-12 21:19:15

0

ň的.h

UILabel *_detailDescriptionLabel; 
} 
    @property (strong, nonatomic) IBOutlet UILabel *detailDescriptionLabel; 

在.M

@synthesize detailDescriptionLabel = _detailDescriptionLabel; 

該行表示屬性 「detailDescriptionLabel」 將有一個名爲 「_detailDescriptionLabel」

類屬性的setter和getter

如果名稱相同,您將擁有

@synthesize detailDescriptionLabel;