用法總結(jié)
1:copy:一般來說捐下,有對應(yīng)Mutab版本的類型,在聲明屬性是,使用copy關(guān)鍵字作為聲明,例如
等等經(jīng)常使用copy關(guān)鍵字蹂午,是因為他們有對應(yīng)的可變類型:NSMutableString坡垫、NSMutableArray、NSMutableDic
,此外block也用過使用copy2:strong:出copy的絕大多數(shù)情況下使用strong關(guān)鍵字画侣。
3:NSMutableString冰悠、NSMutableArray、NSMutableDic不能使用copy類型配乱,否則調(diào)用mubtab版本的方法時直接會拋異常溉卓。
說到底,其實就是不同的修飾符搬泥,對應(yīng)不同的setter方法桑寨,
- strong對應(yīng)的setter方法,是將_property先release(_property release)忿檩,然后將參數(shù)retain(property retain)尉尾,最后是_property = property。
- copy對應(yīng)的setter方法燥透,是將_property先release(_property release)沙咏,然后拷貝參數(shù)內(nèi)容(property copy),創(chuàng)建一塊新的內(nèi)存地址班套,最后_property = property肢藐。
給NSArray使用錯誤關(guān)鍵詞的反例(NSString錯誤同理)
LYWUser.h
@interface LYWUser : NSObject
@property (strong) NSArray *arry_strong;
@property (copy) NSArray *arry_copy;
...
@end
@interface Person : NSObject
@property (strong, nonatomic) NSArray *bookArray1;
@property (copy, nonatomic) NSArray *bookArray2;
@end
//NSArray 為什么使用copy而不用strong,因為有可能在無意識情況下修改數(shù)據(jù)
- (void)test2{
LYWUser *user = [[LYWUser alloc]init];
NSMutableArray *marry = [NSMutableArray arrayWithObjects:@"a",@"b", nil];
user.arry_strong = marry;
user.arry_copy = marry;
[marry addObject:@"c"];
NSLog(@"arry_strong:%@ arry_copy:%@",user.arry_strong,user.arry_copy);
//
// 2016-02-15 15:24:51.028 foo[4488:323714] arry_strong:(
// a,
// b,
// c
// )
// arry_copy:(
// a,
// b
// )
//
//
}
可以看到吱韭,如果使用strong修飾吆豹,在修改marry數(shù)組的值后會使arry_strong的值也發(fā)生變化,這個往往并不是我們希望看到的理盆。
同理痘煤,NSString使用strong也會有這樣的問題
//NSString 為什么使用copy而不用strong,因為有可能在無意識情況下修改數(shù)據(jù)
- (void)test3{
LYWUser *user = [LYWUser factoryA];
NSMutableString *str = [NSMutableString stringWithString:@"a"];
user.str_copy = str;
user.str_strong = str;
[str appendString:@"b"];
NSLog(@"str_copy:%@ str_strong:%@",user.str_copy,user.str_strong);
// 2016-02-15 15:56:55.297 foo[4858:343980] str_copy:a str_strong:ab
}