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

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

问题描述

我怎样才能得到一个列表(的形式的NSArray 的NSDictionary )给定对象的属性在Objective-C?

How can I get a list (in the form of an NSArray or NSDictionary) of a given object attributes 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 attributes. Then I have several classes which extend this parent class, adding a lot of different attributes each.

有没有在整个对象,并返回去什么办法可以实现在的的一个实例方法类,比如说,一个的NSArray 每个(孩子)的类属性为 NSString的是的的父类,所以我可以在以后使用这些的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 attributes as NSStrings that are not on the parent class, so I can later use these NSString for KVC?

推荐答案

我只是设法让自己的答案。通过使用对象 - 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函数,它主要来自苹果code样品(不记得现在的确切来源):

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天全站免登陆