浅拷贝不产生新的对象
深拷贝需要重新创建对象
没啥说的 看代码

1 #import <Foundation/Foundation.h>
2 #import "Person.h"
3 int main(int argc, const char * argv[]) {
4 @autoreleasepool {
5 // 浅拷贝 不产生新的对象
6 // 深拷贝 重新创建对象
7 Person * p = [[Person alloc] init];
8 p.name = @"Tom";
9 p.age = 18;
10 Person * p2 = [p copy];
11 NSLog(@"%p %p",p,p2);
12 NSLog(@"%@ %@",p,p2);
13 // 浅拷贝
14 NSString * str1 = @"abc";
15 NSString * str2 = [str1 copy];
16
17 NSLog(@"%p %p",str1,str2);
18 // 深拷贝
19 NSMutableString * mustr1 = [[NSMutableString alloc] initWithString:@"bcd"];
20 NSMutableString * mustr2 = [mustr1 copy];
21 NSLog(@"%p %p",mustr1,mustr2);
22 // @property的属性 NSString 类型要用copy
23 // 如果指针指向NSString类型的字符串,copy和retain操作是一样的,只会对引用计数retainCount进行操作 copy 为浅拷贝
24 // 如果指针指向NSMutableString的时候,copy操作不仅会对retainCount进行加减,还会重新创建开辟内存空间,存储指向的对象,而retain操作只会对字符串的引用技术进行加减 copy为深拷贝
25 // NSString block copy
26 }
27 return 0;
28 }

1 #import <Foundation/Foundation.h>
2
3 @interface Person : NSObject<NSCopying>
4 @property (nonatomic,copy) NSString * name;
5 @property (nonatomic,assign) int age;
6 @end

1 #import "Person.h"
2
3 @implementation Person
4 - (id)copyWithZone:(NSZone *)zone {
5 // 1 实现对象的直接拷贝 也称为浅拷贝
6 // return self;
7 // 2 深拷贝
8 // 重新创建一个对象
9 Person * p = [[Person alloc] init];
10 p.name = self.name;
11 p.age = self.age;
12 return p;
13 }
14 - (NSString *)description {
15 return [NSString stringWithFormat:@"name:%@ age:%d",_name,_age];
16 }
17 @end
运行结果
2015-11-15 20:47:08.460 02-浅拷贝和深拷贝[749:49637] 0x1006001e0 0x1006003d0
2015-11-15 20:47:08.462 02-浅拷贝和深拷贝[749:49637] name:Tom age:18 name:Tom age:18
2015-11-15 20:47:08.462 02-浅拷贝和深拷贝[749:49637] 0x1000042e0 0x1000042e0
2015-11-15 20:47:08.462 02-浅拷贝和深拷贝[749:49637] 0x103000160 0x64636235
Program ended with exit code: 0