15

我想知道是否可以确定 Objects 属性的类或原始类型。获取所有属性名称和值非常容易。所以回答

那么有没有办法在属性没有值或零值时获取属性类类型?

示例代码

@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
4

2 回答 2

35

在搜索了关于 objc Runtime 的 Apples Documentation并根据这个 SO 答案后,我终于让它工作了。我只是想分享我的结果。

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);
于 2013-05-31T16:57:50.373 回答
4

受@arndt-bieberstein 的 ObjC 回答的启发,我在 Swift 3 中编写了一个解决方案(在早期版本的 Swift 中可能非常相似——如果不相同的话)。你可以在Github上找到它任何继承自.pob lib lintxcodebuildfunc getTypesOfProperties(inClass clazz: NSObject.Type) -> Dictionary<String, Any>?NSObject

该项目的主要工作是这些方法,但请查看Github上的完整代码:

  func getTypesOfProperties(in clazz: NSObject.Type) -> Dictionary<String, Any>? {
        var count = UInt32()
        guard let properties = class_copyPropertyList(clazz, &count) else { return nil }
        var types: Dictionary<String, Any> = [:]
        for i in 0..<Int(count) {
            guard let property: objc_property_t = properties[i], let name = getNameOf(property: property) else { continue }
            let type = getTypeOf(property: property)
            types[name] = type
        }
        free(properties)
        return types
    }

   func getTypeOf(property: objc_property_t) -> Any {
        guard let attributesAsNSString: NSString = NSString(utf8String: property_getAttributes(property)) else { return Any.self }
        let attributes = attributesAsNSString as String
        let slices = attributes.components(separatedBy: "\"")
        guard slices.count > 1 else { return getPrimitiveDataType(withAttributes: attributes) }
        let objectClassName = slices[1]
        let objectClass = NSClassFromString(objectClassName) as! NSObject.Type
        return objectClass
    }

   func getPrimitiveDataType(withAttributes attributes: String) -> Any {
        guard let letter = attributes.substring(from: 1, to: 2), let type = primitiveDataTypes[letter] else { return Any.self }
        return type
    }

   func getNameOf(property: objc_property_t) -> String? {
        guard let name: NSString = NSString(utf8String: property_getName(property)) else { return nil }
        return name as String
    }

它可以提取NSObject.Type类类型继承自的所有属性,NSObject例如NSDate(Swift3: Date)、 ( Swift3 NSString: String?) 和方法)。这是由于Int、Int32、Bool 等限制。由于这些类型不是从 NSObject 继承的,因此调用例如 Int -不会返回 NSObject.Type,而是返回 type 。因此该方法返回而不是。NSNumberAnyvalue types.selfInt.selfAnyDictionary<String, Any>?Dictionary<String, NSObject.Type>?

您可以像这样使用此方法:

class Book: NSObject {
    let title: String
    let author: String?
    let numberOfPages: Int
    let released: Date
    let isPocket: Bool

    init(title: String, author: String?, numberOfPages: Int, released: Date, isPocket: Bool) {
        self.title = title
        self.author = author
        self.numberOfPages = numberOfPages
        self.released = released
        self.isPocket = isPocket
    }
}

guard let types = getTypesOfProperties(inClass: Book.self) else { return }
for (name, type) in types {
    print("'\(name)' has type '\(type)'")
}
// Prints:
// 'title' has type 'NSString'
// 'numberOfPages' has type 'Int'
// 'author' has type 'NSString'
// 'released' has type 'NSDate'
// 'isPocket' has type 'Bool'

您还可以尝试强制Any转换 to NSObject.Type,这对于继承自 的所有属性都将成功NSObject,然后您可以使用标准==运算符检查类型:

func checkPropertiesOfBook() {
    guard let types = getTypesOfProperties(inClass: Book.self) else { return }
    for (name, type) in types {
        if let objectType = type as? NSObject.Type {
            if objectType == NSDate.self {
                print("Property named '\(name)' has type 'NSDate'")
            } else if objectType == NSString.self {
                print("Property named '\(name)' has type 'NSString'")
            }
        }
    }
}

如果您声明此自定义==运算符:

func ==(rhs: Any, lhs: Any) -> Bool {
    let rhsType: String = "\(rhs)"
    let lhsType: String = "\(lhs)"
    let same = rhsType == lhsType
    return same
}

然后你甚至可以检查这样的类型value types

func checkPropertiesOfBook() {
    guard let types = getTypesOfProperties(inClass: Book.self) else { return }
    for (name, type) in types {
        if type == Int.self {
            print("Property named '\(name)' has type 'Int'")
        } else if type == Bool.self {
            print("Property named '\(name)' has type 'Bool'")
        }
    }
}

限制 我还不能在什么时候为这个项目提供支持value types。如果您在 NSObject 子类中声明了这样的属性:var myOptionalInt: Int?我的解决方案将不起作用,因为该方法class_copyPropertyList找不到这些属性。

有人对此有解决方案吗?

于 2016-09-02T10:34:03.813 回答