Objective- C - 循环遍历类中的所有属性? [英] Objective- C - Looping through all properties in a class?
本文介绍了Objective- C - 循环遍历类中的所有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法遍历对象中的所有属性并获取它们的名称"和值".
Is there a way to loop through all properties in an object and get their "name" and "value".
我正在尝试编写一个类别,根据对象的属性名称和值将对象序列化为字符串.我试图阻止为每个类编写编码方法,而是编写一个通用的方法.
I am trying to write a category to serialize objects to a string, based on their property name and values. I'm trying to prevent writing encoding methods for each class, and instead write a generic one.
这可能吗?
推荐答案
您可以使用此代码枚举类中声明的所有属性,以及这些属性的所有属性.我猜你对解析 type 属性更感兴趣.它们在此处有详细说明.
You can use this code to enumerate all properties declared in a class, and all attributes of the properties. I guess you're more interested in parsing the type attribute. They are detailed here.
unsigned int numOfProperties;
objc_property_t *properties = class_copyPropertyList([self class], &numOfProperties);
for ( unsigned int pi = 0; pi < numOfProperties; pi++ ) {
// Examine the property attributes
unsigned int numOfAttributes;
objc_property_attribute_t *propertyAttributes = property_copyAttributeList(properties[pi], &numOfAttributes);
for ( unsigned int ai = 0; ai < numOfAttributes; ai++ ) {
switch (propertyAttributes[ai].name[0]) {
case 'T': // type
break;
case 'R': // readonly
break;
case 'C': // copy
break;
case '&': // retain
break;
case 'N': // nonatomic
break;
case 'G': // custom getter
break;
case 'S': // custom setter
break;
case 'D': // dynamic
break;
default:
break;
}
}
free(propertyAttributes);
}
free(properties);
这篇关于Objective- C - 循环遍历类中的所有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文