objective-c

Looping all properties of a class?


Let's say I have some class that holds a structure of data :

classA:
@property(strong)NSString *name;
@property(strong)NSString *place;
@property(strong)NSString *age;

Then I create an instance of classA and pass it to some other classB ,and this classB should save all A's values to memory (for example to user defaults) .

How can classB, get classA as argument, and then without knowing what properties are inside it, just loop over all of them and save them to memory ?

The goal is to add and remove items from classA without B knowing about them, but B can loop them and save them whatever they are (without using a single array in A).


Solution

  • Based on this Apple Documentation, you can do so.

    You will have to import runtime framework as below,

         #import <objc/runtime.h>
    
    
        id LenderClass = objc_getClass("Lender");
        unsigned int outCount, i;
        objc_property_t *properties = class_copyPropertyList(LenderClass, &outCount);
        for (i = 0; i < outCount; i++) {
            objc_property_t property = properties[i];
            fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property));
        }
    
    
      // This class_copyPropertyList will do that purpose.
      objc_property_t *properties = class_copyPropertyList(LenderClass, &outCount);