OC語言是一個比較好玩語言,就比如爲什麼天殺的爲什麼要出現@property這個語法來刁難我們這些小白呢?不過,細細咀嚼一下,我們還是可以消化的。
屬性 | 使用說明 | 是否爲默認值 |
---|---|---|
readonly | 只讀,只生成讀的存根 | 否 |
readwrite | 可讀寫,生成讀寫的存根 | 是 |
atomic | 線程保護,耗費資源,多線程情況下才使用 | 是 |
nonatomic | 非線程保護 | 否 |
unsafe_unretained | 與weak作用相同,不添加引用計數,當引用對象被銷燬會指向空指針而不是nil,所以爲unsafe | 否 |
weak | 弱引用,不添加引用計數,在避免循環引用的時候使用 | 否 |
copy | 以對象的複製形式傳參 | 否 |
strong | 默認強應用,添加引用計數 | 是 |
爲了方便大家更加直觀地對比內存管理,下面示例代碼,大家可以參考一下:
讀寫特性
類定義
@interface JMItem : NSObject
//定義了只讀
@property (nonatomic,readonly) NSDate *createDate;
//定義了讀寫
@property (nonatomic,readwrite) NSString *name;
//實現
@implementation JMItem
@synthesize name,createDate;
@end
測試代碼
JMItem *item=[[JMItem alloc]init];
item.name=@"my first Item";
//下面語句爲錯誤,因爲定義只讀,所以編譯無法通過
item.createDate=[NSDate dateWithTimeIntervalSinceNow:0];
內存管理特性
類定義
@interface JMItem : NSObject
@property (nonatomic,copy) NSMutableArray *itemArrayCopy;
@property (nonatomic,strong) NSMutableArray *itemArrayStrong;
@property (nonatomic,unsafe_unretained) NSMutableArray *itemArrayUnsafeUnretained;
@property (nonatomic,weak) NSMutableArray *itemArrayWeak;
@property (nonatomic,weak) JMItem *leftChildren;
@property (nonatomic,weak) JMItem *rightChildren;
@property (nonatomic,strong) NSString *name;
-(void)printLog;
@end
@implementation JMItem
@synthesize name;
@synthesize leftChildren,rightChildren;
@synthesize itemArrayCopy,itemArrayStrong,itemArrayWeak,itemArrayUnsafeUnretained;
-(void)printLog{
NSLog(@"Copy:%i,Strong:%i,UnsafeUnretained:%i,Weak:%i",(int)self.itemArrayCopy.count,
(int)self.itemArrayStrong.count,
(int)self.itemArrayUnsafeUnretained.count,
(int)self.itemArrayWeak.count
);
}
@end
JMItem *item=[[JMItem alloc]init];
item.name=@"my first Item";
NSMutableArray *arrayNew=[NSMutableArray arrayWithObjects:@"new new", nil];
item.itemArrayCopy=arrayNew;
item.itemArrayStrong=arrayNew;
item.itemArrayUnsafeUnretained=arrayNew;
item.itemArrayWeak=arrayNew;
[item printLog];
[arrayNew addObject:@"add new"];
[item printLog];
輸出結果
2015-07-28 17:17:28.020 ObjectDemo[12457:894267] Copy:1,Strong:1,UnsafeUnretained:1,Weak:1
2015-07-28 17:17:28.021 ObjectDemo[12457:894267] Copy:1,Strong:2,UnsafeUnretained:2,Weak:2
Program ended with exit code: 0