copy And mutableCopy

copy
通过 copy 产生的对象是不可变对象(eg. NSString、NSArray、NSDictionary)
mutableCopy
通过 mutableCopy 产生的对象是可变对象(eg. NSMutableString、NSMutableArray、NSMutableDictionary)

copy 和 mutableCopy拷贝过程

拷贝前 拷贝方法 拷贝后 是否产生新对象 拷贝类型
NS* copy NS* 浅拷贝
NS* mutableCopy NSMutable* 深拷贝
NSMutable* copy NS* 深拷贝
NSMutable* mutableCopy NSMutable* 深拷贝
  • 注:深拷贝 == 内容拷贝;浅拷贝 == 指针拷贝;

自定义对象使用 copy 和 mutableCopy方法

1、必须实现 NSCopying , NSMutableCopying 协议
2、copyWithZone:方法 和 mutableCopyWithZone:方法必须实现

#import 

@interface ZQObjCopy : NSObject 

@property (nonatomic,  copy) NSMutableString   *name;
@property (nonatomic,  copy) NSString          *mutableStr;
@property (nonatomic,assign) int               age;

@end
#import "ZQObjCopy.h"

@interface ZQObjCopy ()

@end

@implementation ZQObjCopy 

- (id)copyWithZone:(NSZone *)zone{
    ZQObjCopy *objCopy = [[[self class] allocWithZone:zone] init];
    
    objCopy.name = [self.name copy];
    objCopy.mutableStr = [self.mutableStr copy];
    objCopy.age = self.age;
    
    return objCopy;
}

- (id)mutableCopyWithZone:(NSZone *)zone{
    ZQObjCopy *objCopy = [[[self class] allocWithZone:zone] init];
    objCopy.name = [self.name mutableCopy];
    objCopy.mutableStr = [self.mutableStr mutableCopy];
    objCopy.age = self.age;
    
    return objCopy;
}

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