copy分兩種:copy和mutebleCopy
深拷貝:內(nèi)容拷貝惕医,生成新的地址
淺拷貝:指針拷貝精肃,不會生成新的地址
1鳞芙、為什么字符串都用copy
@property (copy, nonatomic) NSString *str;
用copy,可以保證字符串一直是不可變的
2腥例、用copy修飾NSMutableArray
@property (copy, nonatomic) NSMutableArray *arr;
copy修飾婚被,數(shù)組會返回不可變數(shù)組稳析,不能add obj,一般用strong
3洗做、mutableCopy只適用于存在Fundation里特定的對象,如表格中的那些彰居,property屬性中不直接使用
正確使用
NSMutableString *str1 = [NSMutableString stringWithFormat:@"test"];
NSMutableString *str2 = [str1 mutableCopy];
4诚纸、注意NSMutableString初始方式
NSMutableString *str1 = [[NSMutableString alloc] initWithFormat:@"test"]; // 1
NSString *str2 = [str1 copy]; // 深拷貝
NSMutableString *str3 = [str1 mutableCopy]; // 深拷貝
[str1 release];
[str2 release];
[str3 release];
但是
NSMutableString *str1 = [NSMutableString stringWithFormat:@"test"];
NSString *str2 = [str1 copy];//淺拷貝
NSMutableString *str3 = [str1 mutableCopy];//深拷貝
[str1 release];//會報錯,因為是淺拷貝陈惰,指針拷貝畦徘,str1,str2指向同一個指針地址抬闯,不能release兩次
[str2 release];
[str3 release];
NSMutableString的初始方式不同
[NSMutableString stringWithFormat:@"test"];相當(dāng)于直接賦值一個字符串
[[NSMutableString alloc] initWithFormat:@"test"]生成了新地址
5井辆、自定義的class類的不能直接使用copy,要使用必須Copy遵守NSCopying協(xié)議,實現(xiàn)-(id)copywithZone:(NSZone*)zone
@interface MJPerson : NSObject <NSCopying>
@property (assign, nonatomic) int age;
@property (assign, nonatomic) double weight;
@end
- (id)copyWithZone:(NSZone *)zone
{
MJPerson *person = [[MJPerson allocWithZone:zone] init];
person.age = self.age;
// person.weight = self.weight;
return person;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"age = %d, weight = %f", self.age, self.weight];
}
使用
MJPerson *p1 = [[MJPerson alloc] init];
p1.age = 20;
p1.weight = 50;
MJPerson *p2 = [p1 copy];
p2.age = 30;
NSLog(@"%@", p1);
NSLog(@"%@", p2);
[p2 release];
[p1 release];