iOS 内存管理~自定义对象的拷贝

//联系人:石虎QQ: 1224614774昵称:嗡嘛呢叭咪哄

一、浅拷贝

首先创建Person.h和Person.m,实现协议

#Person.h

@interfacePerson : NSObject

@property(nonatomic,copy) NSString *name;

@end

#Person.m

@implementationPerson

@synthesizename;

//实现copyWithZone方法

- (id)copyWithZone:(NSZone*)zone {

Person*p = [[selfclass] allocWithZone:zone];

p.name = [selfname];

return p;

}

@end

二、测试浅拷贝

Person* person = [[Person alloc] init];

[person setName:@"leo"];

NSArray* arr1 = [[NSArray alloc] initWithObjects:person,@"AA",@[@"AA"], [NSMutableArray arrayWithObjects:@"AA",nil],nil];

NSArray* arr2 = [[NSArrayalloc]initWithArray:arr1];

NSArray* arr3 = [[NSArrayalloc]initWithArray:arr1copyItems:YES];

[person setName:@"lily"];

//尝试更改name的值

//获取两个数组里的各自Person对象

Person* p1 = [arr1 objectAtIndex:0];

Person* p2 = [arr2 objectAtIndex:0];

Person* p3 = [arr3 objectAtIndex:0];

NSLog(@"arr1 :%p非集合:%p不可变集合:%p可变集合:%p", arr1, arr1[1], arr1[2], arr1[3]);

NSLog(@"arr2 :%p非集合:%p不可变集合:%p可变集合:%p", arr2, arr2[1], arr2[2], arr2[3]);

NSLog(@"arr3 :%p非集合:%p不可变集合:%p可变集合:%p", arr3, arr3[1], arr3[2], arr3[3]);

NSLog(@"p1:%p  name:%@", p1, p1.name);

NSLog(@"p2:%p  name:%@", p2, p2.name);

NSLog(@"p3:%p  name:%@", p3, p3.name);

arr1 :0x100404520非集合:0x100002090不可变集合:0x1004040a0可变集合:0x100404230

arr2 :0x100404630非集合:0x100002090不可变集合:0x1004040a0可变集合:0x100404230

arr3 :0x100404790非集合:0x100002090不可变集合:0x1004040a0可变集合:0x100404780

p1:0x1004006b0name:lily

p2:0x1004006b0name:lily

p3:0x100404090name:leo

谢谢!!!

你可能感兴趣的:(iOS 内存管理~自定义对象的拷贝)