一:修改copy对象,不影响原对象
@interface VSNCopyItemModel : NSObject<NSCopying,NSMutableCopying>
@property (nonatomic, copy) NSString *itemStr;
@end
@interface VSNCopyModel : NSObject<NSCopying,NSMutableCopying>
@property (nonatomic, copy) NSString *nameStr;
@property (nonatomic, copy) NSArray<VSNCopyItemModel *> *itemModelArr;
@end
@implementation VSNCopyItemModel
- (id)copyWithZone:(NSZone *)zone {
VSNCopyItemModel *model = [[self class] allocWithZone:zone];
model.itemStr = _itemStr;
return model;
}
- (id)mutableCopyWithZone:(NSZone *)zone {
VSNCopyItemModel *model = [[self class] allocWithZone:zone];
model.itemStr = _itemStr;
return model;
}
@end
@implementation VSNCopyModel
- (id)copyWithZone:(NSZone *)zone {
VSNCopyModel *model = [[self class] allocWithZone:zone];
model.nameStr = _nameStr;
model.itemModelArr = [[NSArray alloc] initWithArray:_itemModelArr copyItems:YES];
return model;
}
- (id)mutableCopyWithZone:(NSZone *)zone {
VSNCopyModel *model = [[self class] allocWithZone:zone];
model.nameStr = _nameStr;
model.itemModelArr = [[NSArray alloc] initWithArray:_itemModelArr copyItems:YES];
return model;
}
@end
VSNCopyModel *copyModel1 = [self.mCopyModel copy];
VSNCopyModel *copyModel2 = [self.mCopyModel copy];
NSLog(@"---------%@-__%@",copyModel1, copyModel2);
打印结果:
Printing description of copyModel1:
<VSNCopyModel: 0x600000189700>
Printing description of copyModel1->_itemModelArr:
<__NSSingleObjectArrayI 0x6000003d8460>(
<VSNCopyItemModel: 0x6000003d8450>
)
Printing description of copyModel2:
<VSNCopyModel: 0x6000001890c0>
Printing description of copyModel2->_itemModelArr:
<__NSSingleObjectArrayI 0x6000003d8480>(
<VSNCopyItemModel: 0x6000003d8470>
)
二、
NSArray *arr1 = [self.mutableArr copy];
NSArray *arr2 = [self.mutableArr mutableCopy];
NSMutableArray *arr3 = [self.mutableArr copy];
NSMutableArray *arr4 = [self.mutableArr mutableCopy];
NSArray *arr12 = [self.mArray copy];
NSArray *arr22 = [self.mArray mutableCopy];
NSMutableArray *arr32 = [self.mArray copy];
NSMutableArray *arr43 = [self.mArray mutableCopy];
NSLog(@"%@--%@----%@---%@---%@--%@---%@--%@-",arr1,arr2,arr3,arr4,arr12,arr22,arr32,arr43);
- (NSMutableArray *)mutableArr {
if (!_mutableArr) {
_mutableArr = [NSMutableArray arrayWithArray:@[@"111"]];
}
return _mutableArr;
}
- (NSArray *)mArray {
if (!_mArray) {
_mArray = [NSArray arrayWithObject:@"aaaa"];
}
return _mArray;
}
总结:1、不可变类型的copy是浅拷贝,其他都是深拷贝,和接受值的可变类型无关,
2、copy 返回的对象是不可以变的,mutableCopy返回的对象是可变的