Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 654
velocipedist Avatar asked Jan 18 '23 20:01

velocipedist


1 Answers

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.

like image 117
Forrest Ye Avatar answered Feb 08 '23 16:02

Forrest Ye