我有两个具有相同属性集的类,在协议中使用@property 指令声明,它们都实现了.现在我想知道是否可以使用第二类实例的值自动填充第一类的实例(反之亦然).我希望这种方法是健壮的,这样如果我更改协议中声明的属性,就不需要在复制方法中添加额外的代码.
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.
是的,考虑到确切的上下文,可能有多种方法可以解决此问题.
Yes, given the exact context there could be various approaches to this problem.
目前我能想到的一个方法是先获取源对象的所有属性,然后使用 setValue:value forKey:key
设置目标对象的值.
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.
这篇关于自动将属性值从一个对象复制到另一个类型不同但协议相同的对象 (Objective-C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!