copy
拷贝类别:深拷贝 浅拷贝
深拷贝:拷贝对象 需要创建新的对象
浅拷贝:拷贝指针(对象的地址) 操作的是同一个对象
深拷贝:
当对象调用copy方法时,会调用copyWithZone
-(id)copyWithZone:(NSZone *)zone
{
创建一个新的同类型的对象,将被拷贝对象的数据赋给新创建的对象
Person * p = [[Person alloc] init];
p.name = self.name;
p.age = self.age;
return p;
}
Person * p =[[Person alloc] init];
p.name = @"love";
Person * p2 = [pcopy];
NSLog(@"%p%@", p, p.name);
NSLog(@"%p%@", p2, p2.name);
[p release];
[p2 release];
浅拷贝:操作的是同一个对象,需要对象引用计数加1.
-(id)copyWithZone:(NSZone *)zone
{
实现浅拷贝
Student * s = [self retain];
return s;
}
Student * s1 =[[Student alloc] init];
s1.name =@"Joe";
Student * s2 = [s1copy];
Student对象内部实现的浅拷贝。对被拷贝对象使用了retain。
将指针s1中的对象的地址,复制存储到指针s2中。
NSLog(@"%@%@", s1, s2);
[s1 release];
[s2 release];
NSString
关于NSString的retaincount
如果字符串对象是常量字符串,即对象存储在常量区。
NSString * str1 =@"love";
NSLog(@"%lu",str1.retainCount);
NSString * str2 =[[NSString alloc] initWithFormat:@"love"];
NSLog(@"%lu",str2.retainCount);
NSString * str3 =[[NSString alloc] initWithFormat:@"2324"];
NSLog(@"%lu",str3.retainCount);
使用initWithFormat:创建的字符串对象有两种可能:堆区、常量区
对常量区字符串使用release方法,对常量字符串不会有任何影响。
按照内存管理原则,只要使用了alloc,就要有对应的release。保持一致性,不考虑字符串对象在哪个区。
[str2 release];
[str3 release];
copy mutablecopy
使用copy得到的对象是不可变的
使用mutablecopy得到的对象,是可变的。
字符串、数组、字典
NSArray * array =@[@"sandy", @"Joe"];
NSMutableArray *array2 = [[NSMutableArray alloc] initWithArray:array];
NSLog(@"%@",array2);
NSMutableArray *array3 = [array mutableCopy];
[array3addObject:@"lee"];
NSLog(@"%@",array3);