//联系人:石虎 QQ: 1224614774昵称:嗡嘛呢叭咪哄
一、浅拷贝
首先创建Person.h和Person.m,实现<NSCopying>协议
#Person.h
@interface Person : NSObject <NSCopying>
@property (nonatomic,copy) NSString *name;
@end
#Person.m
@implementation Person
@synthesize name;
//实现copyWithZone方法
- (id)copyWithZone:(NSZone *)zone {
Person *p = [[self class] allocWithZone:zone];
p.name = [self name];
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:0x1004006b0 name:lily
p2:0x1004006b0 name:lily
p3:0x100404090 name:leo
谢谢!!!