copy分两种:copy和mutebleCopy
深拷贝:内容拷贝,生成新的地址
浅拷贝:指针拷贝,不会生成新的地址
1、为什么字符串都用copy
@property (copy, nonatomic) NSString *str;
用copy,可以保证字符串一直是不可变的
2、用copy修饰NSMutableArray
@property (copy, nonatomic) NSMutableArray *arr;
copy修饰,数组会返回不可变数组,不能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"];相当于直接赋值一个字符串
[[NSMutableString alloc] initWithFormat:@"test"]生成了新地址
5、自定义的class类的不能直接使用copy,要使用必须Copy遵守NSCopying协议,实现-(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];