List of class properties in Objective-C

前端 未结 6 1943
南方客
南方客 2020-11-29 17:32

Is there a way to get an array of class properties of certain kind? For example if i have interface like this

@interface MyClass : NSObject
    @property (st         


        
6条回答
  •  清酒与你
    2020-11-29 17:55

    So more precisely, you want dynamic, runtime observaion of the properties, if I got it correctly. Do something like this (implement this method on self, the class you want to introspect):

    #import 
    
    - (NSArray *)allPropertyNames
    {
        unsigned count;
        objc_property_t *properties = class_copyPropertyList([self class], &count);
    
        NSMutableArray *rv = [NSMutableArray array];
    
        unsigned i;
        for (i = 0; i < count; i++)
        {
            objc_property_t property = properties[i];
            NSString *name = [NSString stringWithUTF8String:property_getName(property)];
            [rv addObject:name];
        }
    
        free(properties);
    
        return rv;
    }
    
    - (void *)pointerOfIvarForPropertyNamed:(NSString *)name
    {
        objc_property_t property = class_getProperty([self class], [name UTF8String]);
    
        const char *attr = property_getAttributes(property);
        const char *ivarName = strchr(attr, 'V') + 1;
    
        Ivar ivar = object_getInstanceVariable(self, ivarName, NULL);
    
        return (char *)self + ivar_getOffset(ivar);
    }
    

    Use it like this:

    SomeType myProperty;
    NSArray *properties = [self allPropertyNames];
    NSString *firstPropertyName = [properties objectAtIndex:0];
    void *propertyIvarAddress = [self getPointerOfIvarForPropertyNamed:firstPropertyName];
    myProperty = *(SomeType *)propertyIvarAddress;
    
    // Simpler alternative using KVC:
    myProperty = [self valueForKey:firstPropertyName];
    

    Hope this helps.

提交回复
热议问题