开发者

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

开发者 https://www.devze.com 2023-04-02 05: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 instan

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 protoco开发者_如何学Gol there will be no need to add extra code in the copying methods.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号