2012年4月25日 星期三

OBjectC筆記 -- @property 和 @synthersize

最近終於有點時間,可以寫一個屬於自己的應用程式了。打開了久違的Xcode之後,發現程式碼怎麼看起來都有點陌生呢?? 所以只好把 Object C的重點重新整理一遍囉。

首先介紹的是 @property and @syntherize,其功能就是由 xcode 幫忙產生 setter and getter
原文:@property and @syntherize are what are know as prepocessor macros, which is to say that when you hit "Build and Run" in xcode it knows to replace @property with some prewritten/preformatted block of code


舉例說明如下:原始碼
@interface Fraction : NSObject
{
   int number;
   int tel;
}
@property int number, tel;
...
@end 
@implementation Fraction
@synthesize number, tel;
...
@end 
Xcode看到@property 與 @synthesize 後會分別生成宣告與函數,自動產生number, tel, setNumber, setTel 這四個方法。其產生後的結果如下: 
@property 展開後應如下:
 - (void) setNumber: (int) n;
 - (void) setTel: (int) d;
 - int number(void);
 - int tel(void); 
@synthesize 展開後應如下:
 - (void) setNumber: (int) n
{
   number = n;
}
 - (void) setTel: (int) d
{
   tel = d;
}
 - int number(void)
{
   return number
}
- int tel(void)
{
   return tel;
因此當我們在程式碼中寫 @property 與 @synthesize,之後便可以直接使用Xcode幫忙生成的setter 與 getter 函數。


@property 的屬性,其原形如後,可以設定各種屬性
@property (attributes) type name

屬性列表
  • readwrite:表示此property可讀可寫。
  • readonly:唯讀,也就是說只會產生 getter  函數,而不會有 setter 函數。
  • strong:strong (owning) relationship to the destination object.
  • weak:weak (non-owning) relationship to the destination object.
  • assign:直接設定新值(預設)
  • copy:設值時,將物件複製成一個新的物件,並送出 release message通知原來物件
  • retain:設值時,會設定新值至變數,並送出 release message通知原來物件(可參考下面的例子)
  • nonatomic:指定屬性為nonatomic。預設值為atomic,但是object並沒有定義此關鍵字

註:此處的 atomic 定義如後
Properties are atomic by default so that synthesized accessors provide robust access to properties in a multithreaded environment—that is, the value returned from the getter or set via the setter is always fully retrieved or set regardless of what other threads are executing concurrently.
If you specify strong, copy, or retain and do not specify nonatomic, then in a reference-counted environment, a synthesized get accessor for an object property uses a lock and retains and autoreleases the returned value—the implementation will be similar to the following:


[_internal lock]; // lock using an object-level lock
id result = [[value retain] autorelease];
[_internal unlock];
return result;

If you specify nonatomic, a synthesized accessor for an object property simply returns the value directly.



參考資料