如何让自己写的对象具有拷贝属性
1、对象要满足NSCopying协议
@interface Person : NSObject<NSCopying>
@property(nonatomic, strong)NSString *name;
@property(nonatomic, assign)NSInteger age;
@end
2、实现-(id)copyWithZone:(NSZone *)zone方法
-(id)copyWithZone:(NSZone *)zone{
Person *person = [[Person alloc] init];
if (person) {
person.name = self.name;
person.age = self.age;
}
return person;
}

image.png
同理
如果让自己的类具备mutableCopy方法,并且返回可变类型,必须遵守NSMutableCopying,并实现- (id)mutableCopyWithZone:(nullable NSZone *)zone。
注意:
再此说的copy对应不可变类型和mutableCopy对应可变类型方法,都是遵从系统规则而已。如果你想实现自己的规则,也是可以的。
新建Person对象,进行copy操作,如果遵循不NSCopying协议,不实现协议方法,会报错,但是运行会crash
报错
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Person copyWithZone:]: unrecognized selector sent to instance 0x600000cd2740'
terminating with uncaught exception of type NSException

image.png