Automatically copy property values from one object to another of a different type but the same protocol (Objective-C)

放肆的年华 提交于 2019-12-18 05:07:14

问题


I have two classes with the same set of properties, declared using the @property directive in a protocol, they both implement. Now I was wondering if it is possible to automatically populate an instance of the first class with the values from an instance of the second class (and vice-versa). I would like this approach to be robust, so that if I change the of properties declared in the protocol there will be no need to add extra code in the copying methods.


回答1:


Yes, given the exact context there could be various approaches to this problem.

One I can think of at the moment is to first get all the properties of source object then use setValue:value forKey:key to set the values on the target object.

Code to retrieve all custom properties:

-(NSSet *)propertyNames {
  NSMutableSet *propNames = [NSMutableSet set];
  unsigned int outCount, i;
  objc_property_t *properties = class_copyPropertyList([self class], &outCount);
  for (i = 0; i < outCount; i++) {
    objc_property_t property = properties[i];
    NSString *propertyName = [[[NSString alloc] 
      initWithCString:property_getName(property)] autorelease];
    [propNames addObject:propertyName];
  }
  free(properties);

  return propNames;
}

You may want to checkout the Key-Value Coding Programming Guide for more information.



来源:https://stackoverflow.com/questions/7284391/automatically-copy-property-values-from-one-object-to-another-of-a-different-typ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!