天天看點

聲明property的文法

http://hi.baidu.com/sonnywh/blog/item/5029da11b0bf4a0bb9127bbc.html

聲明property的文法

2011-08-26 13:43聲明property的文法為:

@property (參數1,參數2) 類型 名字;

  如:   

@property(nonatomic,retain) UIWindow *window;

  其中參數主要分為三類:

  讀寫屬性: (readwrite/readonly)   

     setter語意:(assign/retain/copy)

  原子性: (atomicity/nonatomic)

  各參數意義如下:

  readwrite   産生setter\getter方法

  readonly   隻産生簡單的getter,沒有setter。

  assign   預設類型,setter方法直接指派,而不進行retain操作

  retain   setter方法對參數進行release舊值,再retain新值。

  copy   setter方法進行Copy操作,與retain一樣

  nonatomic   禁止多線程,變量保護,提高性能

                    參數類型

參數中比較複雜的是retain和copy,具體分析如下:

getter 分析

  1、 @property(nonatomic,retain)test* thetest;

  @property(nonatomic ,copy)test* thetest;

  等效代碼:

  -(void)thetest

  {

  return thetest;

  }

  2、@property(retain)test* thetest;

  @property(copy)test* thetest;

  等效代碼:

  -(void)thetest

  {

   [thetest retain];

  return [thetest autorelease];

  }

setter分析

  1、   @property(nonatomic,retain)test* thetest;

  @property(retain)test* thetest;

  等效于:

  -(void)setThetest:(test *)newThetest {

  if (thetest!= newThetest) {

   [thetestrelease];

  thetest= [newThetest retain];

  }

  }

   2、@property(nonatomic,copy)test* thetest;

  @property(copy)test* thetest;

  等效于:

  -(void)setThetest:(test *)newThetest {

  if (thetest!= newThetest) {

  [thetestrelease];

  thetest= [newThetest copy];

  }

nonatomic

如果使用多線程,有時會出現兩個線程互相等待對方導緻鎖死的情況(具體可以搜下線程方面的注意事項去了解)。在沒有(nonatomic)的情況下,即預設(atomic),會防止這種線程互斥出現,但是會消耗一定的資源。是以如果不是多線程的程式,打上(nonatomic)即可

retain

代碼說明

如果隻是@property NSString*str;

則通過@synthesize自動生成的setter代碼為:

-(void)setStr:(NSString*)value{

      str=value;

}

如果是@property(retain)NSString*str;

則自動的setter内容為:

-(void)setStr:(NSString*)v{

if(v!=str){

   [str release];

   str=[v retain];

}

}

Objective-C語言關鍵詞,與@property配對使用。

  功能:讓編譯好器自動編寫一個與資料成員同名的方法聲明來省去讀寫方法的聲明。

  如:

  1、在頭檔案中:

  @property int count;  

 等效于在頭檔案中聲明2個方法:

 - (int)count;  

 -(void)setCount:(int)newCount;   

2、實作檔案(.m)中   

@synthesize count;   

等效于在實作檔案(.m)中實作2個方法。

 - (int)count  

 {  

 return count;

 }   

  -(void)setCount:(int)newCount

  {   

          count = newCount;

  }   

以上等效的函數部分由編譯器自動幫開發者填充完成,簡化了編碼輸入工作量。

繼續閱讀