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

前端 未结 1 633
别那么骄傲
别那么骄傲 2020-12-18 09:23

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 autom

相关标签:
1条回答
  • 2020-12-18 09:55

    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 讨论(0)
提交回复
热议问题