我們經(jīng)常會遇到對象需要copy的時(shí)候,也許你會寫一個私有方法為新建對象的所有字段賦值,當(dāng)然沒問題,但是當(dāng)一個對象有幾十個上百個字段的時(shí)候真是太麻煩了,所以我們需要更簡單的方法來實(shí)現(xiàn)這項(xiàng)功能,廢話不多說,利用runtime動態(tài)獲取對象信息的特性實(shí)現(xiàn)如下刀脏,真是太方便了,太方便了超凳,方便了愈污,便了,了轮傍。
步驟一: 遵循NSCopying,NSMutableCopying協(xié)議
@interface xxxModel : NSObject<NSCopying,NSMutableCopying>
@end
步驟二:通過動態(tài)獲取對象信息的方法 實(shí)現(xiàn)copy 和mutablecopy方法
copy 方法實(shí)現(xiàn)
- (id)copyWithZone:(NSZone *)zone
{
id objCopy = [[[self class] allocWithZone:zone] init];
Class clazz = [self class];
u_int count;
objc_property_t* properties = class_copyPropertyList(clazz, &count);
NSMutableArray* propertyArray = [NSMutableArray arrayWithCapacity:count];
for (int i = 0; i < count ; i++)
{
const char* propertyName = property_getName(properties[i]);
[propertyArray addObject:[NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding]];
}
free(properties);
for (int i = 0; i < count ; i++)
{
NSString *name=[propertyArray objectAtIndex:i];
id value=[self valueForKey:name];
if([value respondsToSelector:@selector(copyWithZone:)])
{[objCopy setValue:[value copy] forKey:name];}
else
{[objCopy setValue:value forKey:name];}
}
return objCopy;
}
mutablecopy方法實(shí)現(xiàn)
- (id)mutableCopyWithZone:(NSZone *)zone
{
id objCopy = [[[self class] allocWithZone:zone] init];
Class clazz = [self class];
u_int count;
objc_property_t* properties = class_copyPropertyList(clazz, &count);
NSMutableArray* propertyArray = [NSMutableArray arrayWithCapacity:count];
for (int i = 0; i < count ; i++)
{
const char* propertyName = property_getName(properties[i]);
[propertyArray addObject:[NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding]];
}
free(properties);
for (int i = 0; i < count ; i++)
{
NSString *name=[propertyArray objectAtIndex:i];
id value=[self valueForKey:name];
if([name isEqualToString:@"registeredPlugins"])
{NSLog(@"");}
if([value respondsToSelector:@selector(mutableCopyWithZone:)])
{[objCopy setValue:[value mutableCopy] forKey:name];}
else
{[objCopy setValue:value forKey:name];}
}
return objCopy;
}