首先,声明
@property(nonatomic,copy)NSString * str1; //不可变字符串
@property(nonatomic,copy)NSMutableString * str2;//可变字符串
// %p ,_str1 取地址 %p,&_str1 取指针地址
NSLog(@"str1 = %@ value = %p",_str1,_str1);
NSLog(@"str1 = %@ copy value = %p",[_str1 copy],[_str1 copy]);
NSLog(@"str1 = %@ mutableCopy value= %p",[_str1 mutableCopy],[_str1 mutableCopy]);
NSLog(@"str2 = %@ value = %p",_str2,_str2);
NSLog(@"str2 = %@ copy value = %p",[_str2 copy],[_str2 copy]);
NSLog(@"str2 = %@ mutableCopy value= %p",[_str2 mutableCopy],[_str2 mutableCopy]);
NSMutableString *str4 = [NSMutableString stringWithString:@"hello"];
NSString *str5 = [str4 copy];
NSString * str6 = str4;
NSLog(@"%@ , %p",str4,str4);
[str4 appendString:@"world"];
NSLog(@"%@ , %p",str4,str4);
NSLog(@"%@ , %p",str5,str5);
NSLog(@"%@ , %p",str6,str6);
内存地址都不一样,说明此时都是做内容拷贝、深拷贝
**2016-08-12 10:52:38.390 Copy[1794:93551] str1 = 1 value = 0x1099c3068**
**2016-08-12 10:52:38.390 Copy[1794:93551] str1 = 1 copy value = 0x1099c3068**
**2016-08-12 10:52:38.390 Copy[1794:93551] str1 = 1 mutableCopy value= 0x7fb69ac08ba0**
**2016-08-12 10:52:38.390 Copy[1794:93551] str2 = 1 value = 0x7fb69ac093c0**
**2016-08-12 10:52:38.390 Copy[1794:93551] str2 = 1 copy value = 0xa000000000000311**
**2016-08-12 10:52:38.391 Copy[1794:93551] str2 = 1 mutableCopy value= 0x7fb69ae08260**
**2016-08-12 10:52:38.391 Copy[1794:93551] hello , 0x7fb69ad08090**
**2016-08-12 10:52:38.391 Copy[1794:93551] helloworld , 0x7fb69ad08090**
**2016-08-12 10:52:38.391 Copy[1794:93551] hello , 0xa00006f6c6c65685**
**2016-08-12 10:52:38.391 Copy[1794:93551] helloworld , 0x7fb69ad08090**
**2016-08-12 10:52:38.391 Copy[1794:93551] str1 = 1 , str2 = 1**
- 对非集合类对象的copy操作:
在非集合类对象中:对 immutable 对象进行 copy 操作,是指针复制,mutableCopy 操作时内容复制;对 mutable 对象进行 copy 和 mutableCopy 都是内容复制。用代码简单表示如下:
[immutableObject copy] // 浅复制
[immutableObject mutableCopy] //深复制
[mutableObject copy] //深复制
[mutableObject mutableCopy] //深复制