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

I have two classes with the same set of properties declared using the @property directive in the protocol, both of them are implemented. Now I was wondering if it is possible to automatically populate an instance of the first class with values ​​from an instance of the second class (and vice versa). I would like this approach to be reliable, so if I change the properties declared in the protocol, there will be no need to add additional code to the copy methods.

+4
source share
1 answer

Yes, given the exact context, there may be different approaches to this problem.

, , setValue:value forKey:key .

:

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

.

+9

All Articles