Objective-C @property & @synthesize 使用

來源:互聯網
上載者:User

@property declaration 屬性
為執行個體變數指定屬性(attributes)的途徑, 可讓編譯好器產生 無泄漏和安全執行緒的訪問執行個體變數的方法.

@property 就是對應的編譯器指令

聲明一個與資料成員同名的屬性來省去讀寫函數的聲明
  @interface  Application     {        int versionCode;       int userId;     UserInfo* userInfo;      ApplicationInfo*applicationInfo;
   }     
@property (retain) UserInfo *userInfo;                   // @synthesize userInfo;    @property (retain) ApplicationInfo* applicationInfo ;  // @synthesize applicationInfo;       @end   


聲明property的文法為:
@property (參數) 類型 名字;

這裡的參數主要分為三類:

讀寫屬性: (readwrite/readonly)

setter語意:(assign/retain/copy)

原子性: (atomicity(nonatomic)

assign/retain/copy 決定了以何種方式對資料成員賦予新值
atomicity的預設值是atomic,讀取函數為原子操作。

經常用到的參數是 copy/reain/assign。

在其中選擇一個來確定屬性的setter如何處理這個屬性。很多Objective-C中的object最好使用用retain,一些特別的object(例如:string)使用copy。

assign關鍵字代表setter直接賦值,而不是複製或者保留它。這種機制非常適合一些基本類型,比如NSInteger和CGFloat,或者你並不直接擁有的類型,比如delegates。

readonly關鍵字代表setter不會被產生, 所以它不可以和 copy/retain/assign組合使用。

在實現裡,只需要  

@synthesize mainView;

@synthesize window;

就可代替 繁瑣的setter, getter方法, 這樣就 可讓編譯器自動產生讀寫函數,定義了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.