Automatically copy property values from one object to another of a different type but the same protocol (Objective-C)(自动将属性值从一个对象复制到另一个类型不同但协议相同的对象 (Objective-C))
问题描述
我有两个具有相同属性集的类,在协议中使用@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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:自动将属性值从一个对象复制到另一个类型不同但协议相同的对象 (Objective-C)
基础教程推荐
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
