2012年5月26日 星期六

@property

1.此功為為objective-c 2.0後才加入。
2.主要作用在於存取成員變數。
3.以往可能需撰寫getXxx, setXxx方法存取變數, 現在只要如下寫法
.h檔寫法
@interface X
  {
    float value;
  }
  @property (attribute1, attribute2..) float value; //第4點詳細說明
@end

.m檔寫法, 加入@synthesize同步會產生get, set 方法
@implementation X
  @synthesize value;
@end
4.property也有一些特性以調整變數
  (1)readwrite-可讀可寫(預設)
  (2)readonly-唯讀,只能讀取而不能設定值
  (3)assign-在設值時替換掉舊資料(預設)
         value = newValue;
  (4)retain-在設值時保留新的資料,釋放舊資料, 基本型別不能用retain, 只能用assign
         if(value!=newValue){
             [value release];
             value = [newValue retain];
         }
  (5)copy-在設值時複製一份新資料,釋放舊資料
         if(value!=newValue){
             [value release];
             value = [newValue copy];
         }
  (6)nonatomic-預設為atomic
         automic是在多執行緒環境才會使用到,一般在iphone開發使用nonatomic以提高效率