【轉】 IOS,objective_C中用@interface和 @property 方式聲明變數的區別

來源:互聯網
上載者:User

標籤:

原文: http://blog.csdn.net/ganlijianstyle/article/details/7924446

1.在  @interface :NSObject{} 的括弧中,當然NSObject 是指一個父類,可以是其他的。

形式如下:

@interface GCTurnBasedMatchHelper : NSObject {
    BOOL gameCenterAvailable;
    BOOL userAuthenticated;
}

2.另外一種是直接在 @interface : NSObject{}括弧之後,用 @property 去定義一個變數。

1 @property (assign, readonly) BOOL gameCenterAvailable;

你會發現,有人會再@interface中定義了變數後,又在 @property中重複定義相同的變數,而且很常見。

結果可能是這樣:


@interface GCTurnBasedMatchHelper : NSObject {
    BOOL gameCenterAvailable;
    BOOL userAuthenticated;
}
@property (assign, readonly) BOOL gameCenterAvailable;

而且你可以單獨在@interface中定義變數,而不用@property定義;也可以只用@property去定義,而不在@interface中定義,當然用了@property去定義,一般要在.m檔案中用@synthsize去合成相應的setter,getter方法。否則會得到一個警告。當然@synthsize是可選的,但是是Apple推薦的,不用會有什麼後果,我沒試過,有興趣的童鞋可以試一下。


那這兩種方式有什麼區別呢。

1. 只在@interface中定義變數的話,你所定義的變數只能在當前的類中訪問,在其他類中是訪問不了的;而用@property聲明的變數可以在外部存取。

2.用了@property去聲明的變數,可以使用“self.變數名”的方式去讀寫變數。而用@interface的方式就不可以。

【轉】 IOS,objective_C中用@interface和 @property 方式聲明變數的區別

聯繫我們

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