方案1: 直接实现 <NSMutableCopying>
协议
在自定义类中遵守NSMutableCopying
协议,实现如下代码:
#import <objc/runtime.h>
- (id)mutableCopyWithZone:(NSZone *)zone
{
CustomObject * NEW_MODEL = [[CustomObject alloc] init];
unsigned int count = 0;
Ivar * ivarList = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i++) {
Ivar ivar = ivarList[i];
const char * name = ivar_getName(ivar);
NSString * _key = [NSString stringWithUTF8String:name];
id _val = [self valueForKey:_key];
[NEW_MODEL setValue:_val forKey:_key];
}
free(ivarList);
return NEW_MODEL;
}
方案2: 添加NSObject
扩展
// .h
@interface NSObject (mutableCopy) <NSMutableCopying>
@end
// .m
#import "NSObject+mutableCopy.h"
#import <objc/runtime.h>
@implementation NSObject (mutableCopy)
- (id)mutableCopyWithZone:(NSZone *)zone
{
id NEW_MODEL = [[self class] new];
unsigned int count = 0;
Ivar * ivarList = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i++) {
Ivar ivar = ivarList[i];
const char * name = ivar_getName(ivar);
NSString * _key = [NSString stringWithUTF8String:name];
id _val = [self valueForKey:_key];
[NEW_MODEL setValue:_val forKey:_key];
}
free(ivarList);
return NEW_MODEL;
}
@end