Objective- C - Looping through all properties in a class?

后端 未结 4 2022
清酒与你
清酒与你 2020-12-14 03:09

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, ba

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 03:48

    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);
    

提交回复
热议问题