//copy
NSString * str1 = @"wahaha";
NSString * str2 = [str1 copy];
NSString * str3 = [str1 retain];
NSLog(@"str1 %p str2 %p str4 %p",str1,str2,str3);
NSMutableString *str4 = [NSMutableString stringWithString:@"wahaha"];
NSMutableString *str6 = [str4 retain];
NSMutableString *str5 = [str4 copy];
NSLog(@"str4 %p str5 %p str6 %p",str4,str5,str6);
NSLog(@"%ld %ld %ld",str4.retainCount,str5.retainCount,str6.retainCount);
//str6后追加
[str6 appendString:@"student"];
NSLog(@"str4 %@ str5 %@ str6 %@",str4,str5,str6);
/*
retain:空间一直 引用计数加1
copy: copy对此昂引用计数为1
1.copy 对象是不可变对象时 与retain类似
2.copy 对象时可变对象时 拷贝一份新的空间 ******改空间不可被修改([str5 appendString:@"student"]出错)
释放拷贝对象
*/
//mutableCopy
NSString * str7 = @"wahaha";
NSString * str8 = [str7 mutableCopy];
NSString * str9 = [str7 retain];
NSLog(@"str7 %p str8 %p str9 %p",str7,str8,str9);
/*
mutableCopy:引用计数与copy一致
不管对象是否可变 都会拷贝一份新的空间 *****改空间可以被修改
*/
Person *p = [[Person alloc] init];
Person *p1 = [p copy];
Person *p2 = [p mutableCopy];
/*
自定义类支持copy:
1.该类中必须遵守Copying协议
2.在该类中实现copyWithZone
*/
[p release];
/*
p1:
0x0001->0x0010
0x0011
0x0002->0x0020
0x0021
0x0003->0x0030
0x0021
浅拷贝p2
0x0001->0x0010
0x0011
0x0002->0x0020
0x0021
0x0003->0x0030
0x0021
深拷贝p2:一层一层全部拷贝一份
*/
NSMutableArray * arr1 = [NSMutableArray array];
for (int i =0; i<3; i++) {
Person *p1 = [[Person alloc] init];
p1.name = @"Hello";
[arr1 addObject:p1];
[p1 release];
}
//浅拷贝
NSMutableArray *arr2 =[[NSMutableArray alloc] initWithArray:arr1];
//深拷贝
//使用该方法的前提是 被拷贝对象实现了copyWithZone 方法
NSMutableArray *arr3 = [[NSMutableArray alloc] initWithArray:arr1 copyItems:YES];
NSLog(@"arr1 is %@ arr2 is %@ arr3 is%@",arr1,arr2,arr3);
Person.h
//父类后接<xxxx协议名> 表示该类遵守xxx协议
@interface Person : NSObject<NSCopying,NSMutableCopying>
{
NSInteger _cbID;
NSString *_name;
}
@property (nonatomic ,assign) NSInteger cbID;
@property (nonatomic ,copy) NSString * name;
Person.m
@synthesize name = _name;
@synthesize cbID =_cbID;
//支持拷贝必须实现的方法 该方法在[p copy]时调用
-(id)copyWithZone:(NSZone *)zone
{
Person *p = [[[Person allocWithZone:zone] init] autorelease];
p.name = self.name;
p.cbID = self.cbID;
return p;
}
-(id)mutableCopyWithZone:(NSZone *)zone
{
Person *p = [[[Person allocWithZone:zone] init] autorelease];
p.name = self.name;
p.cbID = self.cbID;
return p;
}