Objective-C - 循环遍历类中的所有属性?

ary*_*axt 17 properties objective-c

有没有办法循环对象中的所有属性并获取其"名称"和"值".

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

这可能吗?

Cos*_*que 23

您可以使用此代码枚举类中声明的所有属性以及属性的所有属性.我猜你对解析type属性更感兴趣.它们在这里详述.

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);
Run Code Online (Sandbox Code Playgroud)