自动将属性值从一个对象复制到另一个不同类型,但使用相同协议(Objective-C) [英] Automatically copy property values from one object to another of a different type but the same protocol (Objective-C)

查看:210
本文介绍了自动将属性值从一个对象复制到另一个不同类型,但使用相同协议(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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆