实现模型数组深拷贝的方法
1、最笨的方法就是通过遍历逐个拷贝元素
NSMutableArray *array = [NSMutableArray array];
for (Person *person in dataSourceAry) {
[array addObject:[person copy]];
}
2、也有人使用归档解档实现数组内部元素拷贝
3、这么好用的一个方法现在才发现(推荐)
- (instancetype)initWithArray:(NSArray<ObjectType> *)array copyItems:(BOOL)flag
这里是系统提供的方法,使用时,需要ObjectType实现NSCopying
NSArray <Person *>*deepCopyAry = [[NSArray alloc]initWithArray:dataSourceAry copyItems:YES];
NSLog(@"<dataSourceAry: %@>", dataSourceAry);
NSLog(@"<deepCopyAry: %@>", deepCopyAry);
[deepCopyAry enumerateObjectsUsingBlock:^(Person *obj, NSUInteger idx, BOOL * _Nonnull stop) {
obj.name = @"弗兰克";
obj.dog.name = @"弗兰克的dog";
}];
NSLog(@"dataSourceAry[0].name = %@", dataSourceAry[0].name);
NSLog(@"deepCopyAry[0].name = %@", deepCopyAry[0].name);
NSLog(@"dataSourceAry[0].dog.name = %@", dataSourceAry[0].dog.name);
NSLog(@"deepCopyAry[0].dog.name = %@", deepCopyAry[0].dog.name);
工程实践:
@interface JJSOrderType : NSObject<NSMutableCopying,NSCopying>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger value;
@property (nonatomic, assign) BOOL bisSelected;
@end
@implementation JJSOrderType
-(id)copyWithZone:(NSZone *)zone{
JJSOrderType *model = [JJSOrderType allocWithZone:zone];
model.name = [_name copy];
model.value = _value;
model.bisSelected = _bisSelected;
return model;
}
-(id)mutableCopyWithZone:(NSZone *)zone{
JJSOrderType *model = [JJSOrderType allocWithZone:zone];
model.name = [_name mutableCopy];
model.value = _value;
model.bisSelected = _bisSelected;
return model;
}
调用:
self.sortTypeArray = [NSMutableArray arrayWithArray: [JJSOrderType mj_objectArrayWithKeyValuesArray:dict]] ;
SearchDiscoverListViewController *left_allVC = self.controllers[0];
// left_allVC.sortTypeArray = [self.sortTypeArray mutableCopy];
left_allVC.sortTypeArray = [NSMutableArray array];// [self.bigCategoryCourseArray mutableCopy];
for (JJSOrderType *model in self.sortTypeArray) {
[left_allVC.sortTypeArray addObject:[model mutableCopy]];
}
NSArray *deepCopyAry = [[NSArray alloc]initWithArray:self.sortTypeArray copyItems:YES];
NSLog(@"<dataSourceAry: %@>", self.sortTypeArray);
NSLog(@"<deepCopyAry: %@>", deepCopyAry);
网友评论