屬性(@property)、@synthesize,propertysynthesize

來源:互聯網
上載者:User

屬性(@property)、@synthesize,propertysynthesize

先前我們學的執行個體變數是這樣的

1 {2     int _age;3     int _height;4     int age;5 }    

後來學屬性

1 @property int age;

看到@property 會自動編譯產生某個成員變數的setter方法和getter方法的聲明

1 - (void)setAge:(int) age;2 - (int)age;

舉例:

@property int _age;

就會編譯產生

- (void)set_age:(int) age;

- (int)_age;

也就是說你怎麼寫執行個體變數就會怎麼編譯產生,為了產生標準的執行個體變數的setter方法和getter方法的聲明,所以屬性不要再加 _ 了,並且setAge大寫

 

既然使用@property有了執行個體變數的setter方法和getter方法的聲明,那麼實現就是@synthesize property

1 // 後面要求寫屬性,明確要對哪個屬性實現一下setter、getter方法2 @synthesize age

看到@synthesize 會自動編譯產生某個成員變數的setter方法和getter方法的實現

1 - (void)setAge:(int)age {2   _age = age;  3 }4 5 - (int)age {6   return age;  7 }

如果硬要去訪問 _age 那個成員變數,就

@synthesize age = _age;

這樣會自動產生age的setter方法和getter方法的實現,並且會去訪問_age這個成員變數

注意:左邊的age:要實現的是age的setter方法和getter方法

   右邊的age:是在實現裡去訪問_age這個成員變數,所以這樣就將屬性和執行個體變數聯絡在一起了

   系統規定成員變數要加 _ 修飾

 

上面的@synthesize age;沒寫後面的成員變數,會預設訪問age

此時:會自動訪問_age這個成員變數,如果不存在,就會自動產生@private類型的_age執行個體變數,在延展中聲明,是私人的

 

XCode4.n之後 @property 即產生聲明有產生實現

1 @property int age;

屬性是執行個體變數_age的一對setter、getter方法的聲明和實現

預設情況下,setter、getter方法中的實現會去訪問 _ 開頭的執行個體變數

 

學到這裡,就清楚了為什麼一開始我們學的時候成員變數以 _ 開頭,其實系統內部是這樣的

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.