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

后端 未结 4 1995
清酒与你
清酒与你 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条回答
  •  -上瘾入骨i
    2020-12-14 03:27

    I don't have comment privileges yet, but to add to @Costique's answer, there is an additional attribute Type value "V" which is the name of the IVar to which a property may be bound (via synthesize). This can be readily discovered with this

    @interface Redacted : NSObject

    @property (atomic, readonly) int foo;

    @end


    @implementation Redacted

    @synthesize foo = fooBar;

    @end

    // for all properties
    unsigned propertyCount = 0;
    objc_property_t *properties = class_copyPropertyList([object class], &propertyCount);
    for (int prop = 0; prop < propertyCount; prop++)
    {
        // for all property attributes
        unsigned int attributeCount = 0;
        objc_property_attribute_t* attributes = property_copyAttributeList(property, &attributeCount);
        for (unsigned int  attr = 0; attr < attributeCount; attr++)
        {
            NSLog(@"Attribute %d: name: %s, value: %s", attr, attributes[attr].name, attributes[attr].value);
        }
    }
    

    2013-07-08 13:47:16.600 Redacted5162:303] Attribute 0: name: T, value: i

    2013-07-08 13:47:16.601 Redacted[5162:303] Attribute 1: name: R, value:

    2013-07-08 13:47:16.602 Redacted[5162:303] Attribute 2: name: V, value: fooBar

提交回复
热议问题