在 Objective-C 中获取对象属性列表 [英] Get an object properties list in Objective-C

查看:44
本文介绍了在 Objective-C 中获取对象属性列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Objective-C 中获取给定对象属性的列表(以 NSArrayNSDictionary 的形式)?

How can I get a list (in the form of an NSArray or NSDictionary) of a given object properties in Objective-C?

想象以下场景:我定义了一个父类,它只扩展了 NSObject,它包含一个 NSString、一个 BOOL 和一个 NSData 对象作为属性.然后我有几个类扩展了这个父类,每个类都添加了很多不同的属性.

Imagine the following scenario: I have defined a parent class which just extends NSObject, that holds an NSString, a BOOL and an NSData object as properties. Then I have several classes which extend this parent class, adding a lot of different properties each.

有什么方法可以在 parent 类上实现一个实例方法,它遍历整个对象并返回,例如,每个(子对象)的 NSArray) 作为 NSStrings 的类属性 not 在父类上,所以我以后可以将这些 NSString 用于 KVC?

Is there any way I could implement an instance method on the parent class that goes through the whole object and returns, say, an NSArray of each of the (child) class properties as NSStrings that are not on the parent class, so I can later use these NSString for KVC?

推荐答案

我刚刚设法自己得到了答案.通过使用 Obj-C 运行时库,我可以按我想要的方式访问属性:

I just managed to get the answer myself. By using the Obj-C Runtime Library, I had access to the properties the way I wanted:

- (void)myMethod {
    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];
        const char *propName = property_getName(property);
        if(propName) {
            const char *propType = getPropertyType(property);
            NSString *propertyName = [NSString stringWithCString:propName
                                                                encoding:[NSString defaultCStringEncoding]];
            NSString *propertyType = [NSString stringWithCString:propType
                                                                encoding:[NSString defaultCStringEncoding]];
            ...
        }
    }
    free(properties);
}

这需要我制作一个getPropertyType"C 函数,该函数主要取自 Apple 代码示例(现在不记得确切的来源):

This required me to make a 'getPropertyType' C function, which is mainly taken from an Apple code sample (can't remember right now the exact source):

static const char *getPropertyType(objc_property_t property) {
    const char *attributes = property_getAttributes(property);
    char buffer[1 + strlen(attributes)];
    strcpy(buffer, attributes);
    char *state = buffer, *attribute;
    while ((attribute = strsep(&state, ",")) != NULL) {
        if (attribute[0] == 'T') {
            if (strlen(attribute) <= 4) {
                break;
            }
            return (const char *)[[NSData dataWithBytes:(attribute + 3) length:strlen(attribute) - 4] bytes];
        }
    }
    return "@";
}

这篇关于在 Objective-C 中获取对象属性列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆