ios 获取对象中属性的类型

/**
  * 返回对象中属性的类型
  * @return NSString 返回属性的类型
 **/
+ (NSString*)checkPropertyName:(id) obj propertyName:(NSString *)name {
    NSString* propertyType;
    
    unsigned int propertyCount;
    objc_property_t* properties = class_copyPropertyList([obj class], &propertyCount);
    for(int i=0;i<propertyCount;i++){
        objc_property_t property = properties[i];
        //属性名称
        const char* propertyName = property_getName(property);
        NSString* propertyNameStr = [NSString stringWithUTF8String:propertyName];
        
        //属性对应的类型名字
        char* typeEncoding = property_copyAttributeValue(property,"T");
        NSString* typeEncodingStr = [NSString stringWithUTF8String:typeEncoding];
        typeEncodingStr = [typeEncodingStr stringByReplacingOccurrencesOfString:@"@" withString:@""];
        typeEncodingStr = [typeEncodingStr stringByReplacingOccurrencesOfString:@"\\" withString:@""];
        
        if ([name isEqualToString:propertyNameStr]) {
            propertyType = typeEncodingStr;
            break;
        }
    }
    free(properties);
    
    return propertyType;
}

猜你喜欢

转载自iaiai.iteye.com/blog/2114720