需求:一个对象数组,然后想将这个数组拷贝出来一份用,修改拷贝的这份数组,保持原始数据不被改变.
我自己的理解:
copy和mutableCopy的区别在于,后者拷贝出来的对象是可变对象,没有别的差别
需要实现NSCopying或者NSMutableCopying协议
(NSMutableArray,NSArray,NSString等实现了该协议)
协议对应方法:
- (id)copyWithZone:(nullable NSZone *)zone
- (id)mutableCopyWithZone:(nullable NSZone *)zone
举例:
实现 NSCopying,NSMutableCopying 协议如果用NSCopying
实现:
- (id)copyWithZone:(nullable NSZone *)zone
如果用NSMutableCopying
实现:
- (id)mutableCopyWithZone:(nullable NSZone *)zone
@interface Model : NSObject<NSCopying,NSMutableCopying>
@property (nonatomic, copy) NSString *str1;
@property (nonatomic, copy) NSString *str2;
@end
@implementation Model
- (id)copyWithZone:(nullable NSZone *)zone{
Model *model1 = [[self class] allocWithZone:zone];
model1.str1 = [_str1 copy];
model1.str2 = [_str2 copy];
return model1;
}
- (id)mutableCopyWithZone:(nullable NSZone *)zone{
Model * model = [[self class] allocWithZone:zone];
model.str1 = [_str1 copy];
model.str2 = [_str2 copy];
return person;
}
@end
实现了协议以后,那么该对象就可以进行拷贝了,下面说说数组是怎么回事
//构造一个Model 数组
NSMutableArray *arr = [NSMutableArray array];
for (int i = 0; i< 3; i++) {
Model *model = [[Model alloc] init];
model.str1 = @"1";
model.str2 = @"2";
NSLog(@"数组%d:---%p",i,model);
[arr addObject:model];
}
那么我想拷贝数组对象,直接NSMutableArray *arr1 = [arr mutableCopy];
是不是这样就可以了arr
内存地址:0x7f8d8b7972a0arr1
内存地址:0x7f8d8b796fe0
显然是不一样的,那么你会说这样就可以了,其实你想多了,断点后看两个数组的元素的地址改变了没有:
结果:
po arr<__NSArrayM 0x7f8d8b7972a0>
(<Model: 0x7f8d8b78f110>,<Model: 0x7f8d8b52b470>,<Model: 0x7f8d8b408830>)
po arr1<__NSArrayM 0x7f8d8b796fe0>
(<Model: 0x7f8d8b78f110>,<Model: 0x7f8d8b52b470>,<Model: 0x7f8d8b408830>)
元素对象是一样的,地址完全一样,所以说数组的指针变了,但是数组元素是没有变的,该如何解决呢?下面这种方式可以是一种解决办法.
NSMutableArray *arr = [NSMutableArray array];
for (int i = 0; i< 3; i++) {
Model *model = [[Model alloc] init];
model.str1 = @"1";
model.str2 = @"2";
NSLog(@"数组%d:---%p",i,model);
[arr addObject:model];}NSMutableArray *arr1 = [NSMutableArray array];
for (Model *model in arr)
{
[arr1 addObject:[model copy]];
}
//这里的copy,就是将arr数组里的每一个对象拷贝一份.//所以Model对象实现
- (id)copyWithZone:(nullable NSZone *)zone方法
苹果提供了数组元素的拷贝方法
解决方法
[[NSMutableArray alloc] initWithArray:arr1 copyItems:YES]