@代表“Objective-C”的標誌,證明您正在使用Objective-C語言
Objective-C語言關鍵詞,@property與@synthesize配對使用。
功能:讓編譯好器自動編寫一個與數據成員同名的方法聲明來省去讀寫方法的聲明。
如:
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;
- }
以上等效的函數部分由編譯器自動幫開發者填充完成,簡化了編碼輸入工作量。
格式:
聲明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) {
- [thetest release];
- 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];
- }
- }
所有者屬性
我們先來看看與所有權有關係的屬性,關鍵字間的對應關係。
屬性值 關鍵字 所有權strong | __strong | 有 |
weak | __weak | 無 |
unsafe_unretained | __unsafe_unretained | 無 |
copy | __strong | 有 |
assign | __unsafe_unretained | 無 |
retain | __strong | 有 |
該屬性值對應 __strong 關鍵字,即該屬性所聲明的變量將成爲對象的持有者。
weak該屬性對應 __weak 關鍵字,與 __weak 定義的變量一致,該屬性所聲明的變量將沒有對象的所有權,並且當對象被破棄之後,對象將被自動賦值nil。
並且,delegate 和 Outlet 應該用 weak 屬性來聲明。同時,如上一回介紹的 iOS 5 之前的版本是沒有 __weak 關鍵字的,所以 weak 屬性是不能使用的。這種情況我們使用 unsafe_unretained。
unsafe_unretained等效於__unsafe_unretaind關鍵字聲明的變量;像上面說明的,iOS 5之前的系統用該屬性代替 weak 來使用。
copy與 strong 的區別是聲明變量是拷貝對象的持有者。
assign一般Scalar Varible用該屬性聲明,比如,int, BOOL。
retain該屬性與 strong 一致;只是可讀性更強一些。
原文地址:http://justcoding.iteye.com/blog/1444548