Objective-C之@property詳解

來源:互聯網
上載者:User

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

屬性的定義(property)

@property (copy, nonatomic) NSString *title;

什麼是assign,copy,retain之間的區別?

  • assign: 簡單賦值,不更改索引計數(Reference Counting)。
  • copy: 建立一個索引計數為1的對象,然後釋放舊對象
  • retain:釋放舊的對象,將舊對象的值賦予輸入對象,再提高輸入對象的索引計數為1

retain的實際文法為:

- (void)setName:(NSString *)newName {    if (name != newName) {       [name release];       name = [newName retain];       // name’s retain count has been bumped up by 1    }}

說了那麼麻煩,其實接下來的話最重要:

?如果你不懂怎麼使用他們,那麼就這樣 ->

  • 使用assign: 對基礎資料類型 (NSInteger,CGFloat)和C資料類型(int, float, double, char, 等等)
  • 使用copy: clone一個對象
  • 使用retain: 對其他NSObject和其子類

nonatomic關鍵字:

atomic是Objc使用的一種線程保護技術,基本上來講,是防止在寫未完成的時候被另外一個線程讀取,造成資料錯誤。而這種機制是耗費系統資源的,所以在iPhone這種小型裝置上,如果沒有使用多線程間的通訊編程,那麼nonatomic是一個非常好的選擇。

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

聲明一個與資料成員同名的屬性來省去讀寫函數的聲明

@interface Application
{
unsigned int root_port;
unsigned int notifier;
UIWindow *window;
MainView *mainView;
}

- (void)applicationDidFinishLaunching:(id)arg1;
- (void)applicationWillSuspend;
- (void)dealloc;
@property(retain) UIView *mainView; // @synthesize mainView;
@property(retain) UIWindow *window; // @synthesize window;

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

定義了property, 使用者,可以 點號(.) 來存取屬性了,哈哈,有點像C++了

相關文章

聯繫我們

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