2

Get declared property for object

 2 years ago
source link: https://fann.im/blog/2012/11/26/get-declared-property-for-object-in-objective-c/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Get declared property for object

Nov 26, 2012

获取对象的 property 属性列表:

objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount)
objc_property_t *protocol_copyPropertyList(Protocol *proto, unsigned int *outCount)

sample, via Declared Properties:

#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));
}
free(properties);

拿到 property 列表就可以很方便做一些东西,比如 autodescribe,根据列表取值然后组装成对象 description。再比如配合 NSCoder 做 NSObject 的序列化

- (id)initWithCoder:(NSCoder *)decoder
{
    self = [super init]
    if (self)
    {
        Class clazz = [self class];
        NSUInteger count;

        objc_property_t *properties = class_copyPropertyList(clazz, &count);
        NSMutableArray *propertyArray = [NSMutableArray arrayWithCapacity:count];
        for (int i = 0; i < count ; i++)
        {
            objc_property_t property = properties[i];
            const char *propertyName = property_getName(property);
            [propertyArray addObject:[NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding]];
        }
        free(properties);

        for (NSString *name in propertyArray)
        {
            id value = [decoder decodeObjectForKey:name];
            [self setValue:value forKey:name];
        }
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder
{
    Class clazz = [self class];
    NSUInteger count;

    objc_property_t *properties = class_copyPropertyList(clazz, &count);
    NSMutableArray *propertyArray = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i < count ; i++)
    {
        objc_property_t property = properties[i];
        const char *propertyName = property_getName(property);
        [propertyArray addObject:[NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding]];
    }
    free(properties);

    for (NSString *name in propertyArray)
    {
        id value = [self valueForKey:name];
        [coder encodeObject:value forKey:name];
    }
}

也可以拿到成员变量列表: class_copyIvarList(Class cls, unsigned int *outCount). Objective-C Runtime 有很多东西可以学习的。

Was this page helpful?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK