先来打一下实例:
创建一个Person类:
Person.h:
#import <Foundation/Foundation.h> @interface Person : NSObject<NSCopying> @property(nonatomic,assign) int age; @property(nonatomic,retain) NSString *name; @end
#import "Person.h" @implementation Person - (id)init { self = [super init]; if (self) { self.name = @"xiaoming"; self.age = 22; } return self; } //构造拷贝函数,虽然说内存管理的原则是谁retain谁release,但是对copy来说比较特殊,是放在外面release的 -(id)copyWithZone:(NSZone *)zone { Person *p = [[Person allocWithZone:zone] init]; p.name = self.name; //浅拷贝,只是拷贝了地址 p.age = self.age; //深拷贝 //p.name = [self.name copy];//内容拷贝一份 return p; } - (void)dealloc { [_name release]; [super dealloc]; } @end
main:
#import <Foundation/Foundation.h> #import "Person.h" int main(int argc, const char * argv[]) { @autoreleasepool { Person *p = [[Person alloc] init]; p.age = 11; NSMutableString *str = [NSMutableString stringWithFormat:@"xiaohua"]; p.name = str; NSLog(@"person age = %d name = %@",p.age,p.name); Person *p1 = [p copy]; [str appendString:@"1"]; //在原来的基础上加1 NSLog(@"person age = %d name = %@",p.age,p.name); //验证原来的对象是否改变 NSLog(@"p1 age = %d name = %@",p1.age,p1.name); //打印当然的拷贝对象,这个要看前面的拷贝实现的函数是深拷贝还是浅拷贝 [p1 release]; [p release]; } return 0; }
浅拷贝结果:
2013-08-05 11:35:39.688 对象拷贝[862:303] person age = 11 name = xiaohua
2013-08-05 11:35:39.690 对象拷贝[862:303] person age = 11 name = xiaohua1
2013-08-05 11:35:39.691 对象拷贝[862:303] p1 age = 11 name = xiaohua1
深拷贝:2013-08-05 11:39:26.579 对象拷贝[892:303] person age = 11 name = xiaohua
2013-08-05 11:39:26.581 对象拷贝[892:303] person age = 11 name = xiaohua1
2013-08-05 11:39:26.582 对象拷贝[892:303] p1 age = 11 name = xiaohua
转载于:https://blog.51cto.com/dingxiaowei/1366465