#import
/*
1,Copy的基本概念
>通过Copy,可以产生一个新的副本
2,如何使用Copy
>一个对象可以调用Copy和MutableCopy来创建一个副本对象
>copy:创建的是不可变副本(如NSString,NSArray,NSDictionary)
需要遵守NSCopy协议,实现copyWithZone方法
>mutableCopy:创建的是不可变副本(如NSMutableString,NSMutableArray,NSMutableDictionary)
需要遵守NSMutableCopy协议,实现mutableCopyWithZone方法
*/
int main(int argc, const char * argv[]) {
/*
3,产生新对象的判断方式:
>原对象的修改不会影响副本对象,副本对象的修改不会影响原对象
*/
NSString *srcStr = @"ljs";
NSString *copyStr = [srcStr copy];
NSLog(@"srcStr = %@, copyStr = %@",srcStr,copyStr);
NSLog(@"srcStr = %p, copyStr = %p",srcStr,copyStr);
NSString *srcStr1 = @"ljs";
NSMutableString *copyStr1 = [srcStr1 mutableCopy];
[copyStr1 appendFormat:@"m"];
NSLog(@"srcStr = %@, copyStr = %@",srcStr1,copyStr1);
NSLog(@"srcStr = %p, copyStr = %p",srcStr1,copyStr1);
NSMutableString *srcStr3 = [NSMutableString stringWithFormat:@"ljs"];
NSString *copyStr3 = [srcStr3 copy];
[srcStr3 appendFormat:@"m"];
NSLog(@"srcStr = %@, copyStr = %@",srcStr3,copyStr3);
NSLog(@"srcStr = %p, copyStr = %p",srcStr3,copyStr3);
NSMutableString *srcStr4 = [NSMutableString stringWithFormat:@"ljs"];
NSMutableString *copyStr4 = [srcStr4 mutableCopy];
[copyStr4 appendFormat:@"m"];
NSLog(@"srcStr = %@, copyStr = %@",srcStr4,copyStr4);
NSLog(@"srcStr = %p, copyStr = %p",srcStr4,copyStr4);
/*
总结:
(1)如果通过不可变对象调用copy方法,生成一个副本对象,那么,副本对象跟原对象都指向同一块内存地址,共享一块存储空间。
而其他copy,mutableCopy方式创建出来的对象都是一个副本对象,副本对象都有一块新的存储空间,修改内容,并不会影响彼此。
(2)通过拷贝,没有生成新对象,称之为浅拷贝,本质是指针拷贝
而生成新对象,称之为深拷贝,本质是创建一个新的对象
(3)内存管理:
原则:一次alloc对应一次release
一次retain对应一次release
一次copy对应一次release
有加就有减,一一对应
>如果是浅拷贝,那么,系统会对原来的对象进行一次retain
>如果是深拷贝,那么,会生成一个新的对象,系统不会对原对象进行一次retain操作,但我们需要对新的对象进行一次release
*/
return 0;
}
//2015-12-23 19:04:58.829 16,Copy,MutableCopy的应用与内存管理[4024:645912] srcStr = ljs, copyStr = ljs
//2015-12-23 19:04:58.830 16,Copy,MutableCopy的应用与内存管理[4024:645912] srcStr = 0x100001038, copyStr = 0x100001038
//2015-12-23 19:04:58.830 16,Copy,MutableCopy的应用与内存管理[4024:645912] srcStr = ljs, copyStr = ljsm
//2015-12-23 19:04:58.830 16,Copy,MutableCopy的应用与内存管理[4024:645912] srcStr = 0x100001038, copyStr = 0x1004003b0
//2015-12-23 19:04:58.830 16,Copy,MutableCopy的应用与内存管理[4024:645912] srcStr = ljsm, copyStr = ljs
//2015-12-23 19:04:58.830 16,Copy,MutableCopy的应用与内存管理[4024:645912] srcStr = 0x100700080, copyStr = 0x736a6c35
//2015-12-23 19:04:58.830 16,Copy,MutableCopy的应用与内存管理[4024:645912] srcStr = ljs, copyStr = ljsm
//2015-12-23 19:04:58.830 16,Copy,MutableCopy的应用与内存管理[4024:645912] srcStr = 0x100109210, copyStr = 0x100107420
//Program ended with exit code: 0