1腋逆、各個(gè)屬性選項(xiàng)的意義
Objective-c中旁壮,@property選項(xiàng)有assign监嗜、retain、unsafe_unretain抡谐、strong裁奇、weak和copy六個(gè)選項(xiàng),其中strong麦撵、weak刽肠、unsafe_unretain是在引入ARC后新添加的選項(xiàng)。
strong與unsafe_unretain主要用在ARC下免胃,作用分別與retain和assign相同音五,weak則是ARC專用。
2羔沙、ARC下屬性與修飾符的關(guān)系
聲明的屬性 | 所有權(quán)修飾符 |
---|---|
assign | __unsafe_unretained |
weak | __weak |
copy | __strong (但是賦值的是被復(fù)制的對(duì)象) |
retain | __strong |
strong | __strong |
unsafe_unretained | __unsafe_unretained |
以上各種屬性賦值給指定的屬性中就相當(dāng)于賦值給附加各屬性對(duì)應(yīng)的所有權(quán)修飾符的變量中躺涝。只有copy屬性不是簡(jiǎn)單的賦值,它賦值是通過NSCopying接口的copyWithZone:方法復(fù)制賦值源所生成的對(duì)象扼雏。
3坚嗜、MRC下的屬性與setter/getter方法
所有權(quán)修飾符是ARC中新增的內(nèi)容,在MRC下需要通過retain/release等方法手動(dòng)管理內(nèi)存
MRC下呢蛤,可以使用的與內(nèi)存管理相關(guān)屬性關(guān)鍵字有assign、retain棍郎、copy其障,對(duì)應(yīng)的setter/getter方法如下
//assign的setter
- (void)setObj:(NSInteger)obj
{
_obj = obj;
}
//retain的setter方法
- (void)setObj:(id)obj
{
if(_obj != obj) {
[_obj release];
_obj = [obj retain];
}
}
//copy的setter方法
- (void)setObj:(id)obj
{
if(_obj != obj) {
[_obj release];
_obj = [obj copy];
}
}
//assign的getter方法
- (NSInteger)obj
{
return _obj;
}
//retain與copy的getter方法
- (id)obj
{
return [[_obj retain] autorelease];
}
4、ARC下屬性與setter/getter方法
根據(jù)ARC屬性與所有權(quán)修飾符的關(guān)系涂佃,屬性對(duì)應(yīng)變量已加上對(duì)應(yīng)的修飾符励翼,故setter/getter方法如下
//property(copy) NSObject *obj;
-(void)setObj:(id)obj
{
//變量_obj的修飾符為__strong,但是copy需要通過NSCopying接口的copyWithZone:方法復(fù)制賦值源所生成的對(duì)象
_obj = [obj copy];
}
//property(strong/weak/assign等剩余屬性) NSObject *obj;
- (void)setObj:(id)obj
{
//變量_obj修飾符為__strong, __weak, __unsafe_unretained等
_obj = obj;
}