gpt4 book ai didi

objective-c - Objective- C - 遍历类中的所有属性?

转载 作者:太空狗 更新时间:2023-10-30 03:15:38 25 4
gpt4 key购买 nike

有没有办法遍历对象中的所有属性并获取它们的“名称”和“值”。

我正在尝试编写一个类别,以根据对象的属性名称和值将对象序列化为字符串。我试图避免为每个类编写编码方法,而是编写一个通用方法。

这可能吗?

最佳答案

您可以使用此代码枚举类中声明的所有属性,以及属性的所有属性。我猜你对解析 type 属性更感兴趣。它们很详细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 - Objective- C - 遍历类中的所有属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9252147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com