copy、mutableCopy

一:修改copy对象,不影响原对象

@interface VSNCopyItemModel : NSObject

@property (nonatomic, copy) NSString *itemStr;

@end

@interface VSNCopyModel : NSObject

@property (nonatomic, copy) NSString *nameStr;
@property (nonatomic, copy) NSArray *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:

Printing description of copyModel1->_itemModelArr:
<__NSSingleObjectArrayI 0x6000003d8460>(

)
Printing description of copyModel2:

Printing description of copyModel2->_itemModelArr:
<__NSSingleObjectArrayI 0x6000003d8480>(

)

二、

    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返回的对象是可变的

你可能感兴趣的:(copy、mutableCopy)