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

后端 未结 4 2025
清酒与你
清酒与你 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

    I use the following Category on NSObject to say, for example, NSLog(@"%@", [someObject propertiesPlease]);, resulting in a log entry like…

    someObject: {
        color = "NSCalibratedRGBColorSpace 0 0 1 1";
        crayon = Blueberry;
    }
    

    NSObject+Additions.h

    @interface NSObject (Additions)
    - (NSDictionary *)propertiesPlease;
    @end
    

    NSObject+Additions.m

    @implementation NSObject (Additions)
    - (NSDictionary *)propertiesPlease {
    NSMutableDictionary *props = [NSMutableDictionary dictionary];
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    for (i = 0; i < outCount; i++) {
       objc_property_t property = properties[i];
       NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property)];
       id propertyValue = [self valueForKey:(NSString *)propertyName];
       if (propertyValue) [props setObject:propertyValue forKey:propertyName];
    }
       free(properties);
       return props;
    }
    @end
    

提交回复
热议问题