OC學習那些事:@property和@synthesize

來源:互聯網
上載者:User

1.@property 

只用在.h檔案中@interface關鍵字中 

當編譯器遇見@property時,會自動延伸成getter和setter方法的聲明。 

//等效 @property int age;  -(int)age; -(void)setAge:(int)newAge; 

注意:在XCode4.5環境下,檢測到@property時,自動在.m檔案中添加@synthesize
age = _age。如.h檔案,沒有聲明_age變數,則自動在.m檔案中添加私人的成員變數_age。 

2.@synthesize 

只用在.m檔案中的@implements關鍵字。 

當編譯器遇見@synthesize時,會自動延伸成getter和setter方法的實現,預設訪問同名的成員變數。 

@synthesize age = _age;代表get方法和set方法會訪問_age這個成員變數。 

//等效 @synthesize age = _age;  -(void)setAge:(int)newAge {     _age = newAge; }  -(int)age {     return _age; }  

注意:如果沒有找到成員變數,則自動產生私人的同名的成員變數。 

3.完整的使用 

Person.h檔案 

@interface Person:NSObject {     int _ID;     float _weight; } @property int ID; @property float weight;  @end 

Person.m檔案 

@implement Person  @synthesize ID = _ID; @synthesize weight = _weight;  @end 

4.綜合使用 

以上@property和@synthesize關鍵字和getter/setter方法可以混合使用。 

如果在某種特殊的需求下,手動實現了getter/setter方法時,則@synthesize無效。 

Person.h檔案 

@interface Person:NSObject {     int _ID;     float _weight; } @property int ID; @property float weight;  @end 

Person.m檔案 

@implement Person  -(void)setID:int newID {     //在getter/setter方法中,有特殊的操作     _ID = newID *100; }      -(int)ID {     return _ID; } @end

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.