有时候项目中会有些model需要copy, 这个时候就需要实现 NSCopying 协议方法copyWithZone了
但是很多时候都是一个个属性来赋值, 这样做属性少还可以, 但是如果有很多属性呢, 难道也要一个一个去赋值吗? 显然还需要更好的解决办法
以下是用runtime来实现copyWithZong方法的姿势:
// copy代码请下拉:
- (id)copyWithZone:(NSZone *)zone {
id objCopy = [[[self class] allocWithZone:zone] init];
// 1.获取属性列表
unsigned int propertyCount = 0;
objc_property_t * propertyArray = class_copyPropertyList([self class], &propertyCount);
for (int i=0; i<propertyCount; i++) {
objc_property_t property = propertyArray[i];
// 2.属性名字
const char * propertyName = property_getName(property);
NSString * key = [NSString stringWithUTF8String:propertyName];
// 3.通过属性名拿到属性值
id value=[self valueForKey:key];
NSLog(@"name:%s,value:%@",propertyName,value);
// 4.判断 值对象是否响应copyWithZone
if ([value respondsToSelector:@selector(copyWithZone:)]) {
//5. 设置属性值
[objCopy setValue:[value copy] forKey:key];
}else{
[objCopy setValue:value forKey:key];
}
}
//*****切记需要手动释放
free(propertyArray);
return objCopy;
}