加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 属性类型或类使用反射

发布时间:2020-12-16 05:51:13 所属栏目:百科 来源:网络整理
导读:我想知道是否可以确定对象属性的类或原始类型.获取所有属性名称和值非常简单. SO answer 那么有没有办法得到属性类类型,而属性没有值或零值? 示例代码 @interface MyObject : NSObject@property (nonatomic,copy) NSString *aString;@property (nonatomic,c
我想知道是否可以确定对象属性的类或原始类型.获取所有属性名称和值非常简单. SO answer

那么有没有办法得到属性类类型,而属性没有值或零值?

示例代码

@interface MyObject : NSObject
@property (nonatomic,copy) NSString *aString;
@property (nonatomic,copy) NSDate *aDate;
@property                   NSInteger aPrimitive;
@end

@implementation MyObject
@synthesize aString;
@synthesize aDate;
@synthesize aPrimitive;

- (void)getTheTypesOfMyProperties {
    unsigned int count;
    objc_property_t* props = class_copyPropertyList([self class],&count);
    for (int i = 0; i < count; i++) {
        objc_property_t property = props[i];

        // Here I can easy get the name or value
        const char * name = property_getName(property);

        // But is there any magic function that can tell me the type?
        // the property can be nil at this time
        Class cls = magicFunction(property);
    }
    free(props);
}

@end

解决方法

通过 Apples Documentation about objc Runtime搜索,根据 this SO answer,我终于得到了工作.我只是想分享我的结果.
unsigned int count;
objc_property_t* props = class_copyPropertyList([MyObject class],&count);
for (int i = 0; i < count; i++) {
    objc_property_t property = props[i];
    const char * name = property_getName(property);
    NSString *propertyName = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
    const char * type = property_getAttributes(property);
    NSString *attr = [NSString stringWithCString:type encoding:NSUTF8StringEncoding];

    NSString * typeString = [NSString stringWithUTF8String:type];
    NSArray * attributes = [typeString componentsSeparatedByString:@","];
    NSString * typeAttribute = [attributes objectAtIndex:0];
    NSString * propertyType = [typeAttribute substringFromIndex:1];
    const char * rawPropertyType = [propertyType UTF8String];

    if (strcmp(rawPropertyType,@encode(float)) == 0) {
        //it's a float
    } else if (strcmp(rawPropertyType,@encode(int)) == 0) {
        //it's an int
    } else if (strcmp(rawPropertyType,@encode(id)) == 0) {
        //it's some sort of object
    } else {
        // According to Apples Documentation you can determine the corresponding encoding values
    }

    if ([typeAttribute hasPrefix:@"T@"]) {
        NSString * typeClassName = [typeAttribute substringWithRange:NSMakeRange(3,[typeAttribute length]-4)];  //turns @"NSDate" into NSDate
        Class typeClass = NSClassFromString(typeClassName);
        if (typeClass != nil) {
            // Here is the corresponding class even for nil values
        }
    }

}
free(props);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读