Runtime二 之让子对象自动实现copy/mutablecopy

我们经常会遇到对象需要copy的时候,也许你会写一个私有方法为新建对象的所有字段赋值,当然没问题,但是当一个对象有几十个上百个字段的时候真是太麻烦了,所以我们需要更简单的方法来实现这项功能,废话不多说,利用runtime动态获取对象信息的特性实现如下,真是太方便了,太方便了,方便了,便了,了。

步骤一: 遵循NSCopying,NSMutableCopying协议
@interface xxxModel : NSObject
@end

步骤二:通过动态获取对象信息的方法 实现copy 和mutablecopy方法

copy 方法实现

- (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方法实现

- (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;
}

你可能感兴趣的:(Runtime二 之让子对象自动实现copy/mutablecopy)