copy
copy语法的目的是改变副本的时候,不会影响到源对象。
一、一个对象使用copy或mutableCopy方法可以创建对象的副本。
二、copy - 需要先实现NSCoppying协议,创建的是不可变副本(如NSString、NSArray、NSDictonnary)
实现NSCoppying协议,需要实现以下方法
- (id)copyWithZone:(NSZone *)zone {
Student *copy = [[Student allocWithZone:zone] init];
//拷贝名字给副本对象。
copy.name = self.name;
return copy;
}
三、mutableCopy - 需要先实现NSMutableCopying协议,创建的事可变副本(如NSMUtableString、NSMutableArray、NSMutableDictionary)
四、深复制:内容拷贝,源对象和副本指向的是不同的两个对象。源对象引用计数器不变,副本计数器设置为1.
浅复制:指针拷贝,源对象和副本指向的是同一个对象,对象的引用计数器+1,其实相当于做了一次retain操作。
五、只有不可变对象创建不可变副本(copy)才是浅复制,其他都是深复制。
六、#pragma mark 演示字符串的拷贝(深拷贝)。
void stringMutableCopy() {
NSString *string = [[NSString alloc] initWithFormat:@"age is %i",10];
//产生了一个新对象,计数器为1.
NSMutableString *str = [string mutableCopy];
NSLog(@"str:%zi", [str retainCount]);
NSLog(@"string:%zi", [string retainCount]);
//调用mutableCopy产生的是可变副本,str和string不是相同对象。
NSLog(@"%i",str == string);
//副本改变了,源对象不变。
[str appendString:@"abcd"];
NSLog(@"string:%@",string);
NSLog(@"str:%@",str);
[str release];
[string release];
}
七、#pragma mark 演示字符串的拷贝(浅拷贝)。
void stringCopy1() {
NSString *string = [[NSString alloc] initWithFormat:@"age is %i",10];
//调用copy产生的是不可变副本,由于源对象本身就不可变,所有为了性能着想,copy会直接返回源对象本身,源对象计数器+1,str1和string是相同对象,
NSMutableString *str = [string copy];
NSLog(@"%@",string);
NSLog(@"%i", str == string);
[str release];
[string release];
}
八、#pragma mark 可变字符串的copy(深拷贝)
void mutableStringCopy() {
NSMutableString *string = [NSMutableString stringWithFormat:@"age is %i ",10];
NSString *str = [string copy];
NSLog(@"%i",str == string);
[str release];
[string release];
}
九、#pragma mark 演示Student的name的copy
void studentNameCopy() {
Student *stu = [Student studentWithName:@"abc"];
NSMutableString *string = [NSMutableString stringWithFormat:@"age is %i", 10];
stu.name = string;
[string appendString:@"123"];
NSLog(@"name = %@", stu.name);
NSLog(@"string = %@", string);
}
十、#pragma mark 演示Student的copy
void studentCopy() {
Student *stu = [Student studentWithName:@"stu"];
Student *stu1 = [stu copy];
NSLog(@"%@",stu1);
}
十一、#pragma mark 演示继承的copy,GoodStudent类继承Student,Student有成员变量name,GoodStudent有成员变量age.
void goodStudentCopy() {
GoodStudent *stu = [GoodStudent goodStudentWithAge:10 andName:@"good"];
NSLog(@"%@",stu);
GoodStudent *stu1 = [stu copy];
stu1.name = @"good1";
stu1.age = 11;
NSLog(@"%zi",stu.retainCount);
NSLog(@"%zi", stu1.retainCount);
NSLog(@"%@",stu1);
[stu1 release];
}
浙公网安备 33010602011771号