获取Swift类的属性列表

时间:2014-09-02 20:55:41

标签: serialization enums swift

我正在尝试获取一个快速类的属性列表。还有一个类似的问题herehere。除了某些类型之外我没有从class_copyPropertyList返回所有内容。我到目前为止测试过的是Int?和枚举。我在下面有一个示例课程,我正在尝试。

enum PKApiErrorCode: Int {
    case None = 0
    case InvalidSignature = 1
    case MissingRequired = 2
    case NotLoggedIn = 3
    case InvalidApiKey = 4
    case InvalidLogin = 5
    case RegisterFailed = 6
}

class ApiError: Serializable {
    let code: PKApiErrorCode?
    let message: String?
    let userMessage: String?

    init(error: JSONDictionary) {
        code = error["errorCode"] >>> { (object: JSON) -> PKApiErrorCode? in
            if let c = object >>> JSONInt {
                return PKApiErrorCode.fromRaw(c)
            }

            return nil
        }

        message = error["message"] >>> JSONString
        userMessage = error["userMessage"] >>> JSONString
    }
}

Serializable类(在https://gist.github.com/turowicz/e7746a9c035356f9483d的帮助下)

public class Serializable: NSObject, Printable {
    override public var description: String {
        return "\(self.toDictionary())"
    }
}

extension Serializable {
     public func toDictionary() -> NSDictionary {
        var aClass : AnyClass? = self.dynamicType
        var propertiesCount : CUnsignedInt = 0
        let propertiesInAClass : UnsafeMutablePointer<objc_property_t> = class_copyPropertyList(aClass, &propertiesCount)
        var propertiesDictionary : NSMutableDictionary = NSMutableDictionary()
        for var i = 0; i < Int(propertiesCount); i++ {

            var property = propertiesInAClass[i]
            var propName = NSString(CString: property_getName(property), encoding: NSUTF8StringEncoding)
            var propType = property_getAttributes(property)
            var propValue : AnyObject! = self.valueForKey(propName);
            if propValue is Serializable {
                propertiesDictionary.setValue((propValue as Serializable).toDictionary(), forKey: propName)
            } else if propValue is Array<Serializable> {
                var subArray = Array<NSDictionary>()
                for item in (propValue as Array<Serializable>) {
                    subArray.append(item.toDictionary())
                }
                propertiesDictionary.setValue(subArray, forKey: propName)
            } else if propValue is NSData {
                propertiesDictionary.setValue((propValue as NSData).base64EncodedStringWithOptions(nil), forKey: propName)
            } else if propValue is Bool {
                propertiesDictionary.setValue((propValue as Bool).boolValue, forKey: propName)
            } else if propValue is NSDate {
                var date = propValue as NSDate
                let dateFormatter = NSDateFormatter()
                dateFormatter.dateFormat = "Z"
                var dateString = NSString(format: "/Date(%.0f000%@)/", date.timeIntervalSince1970, dateFormatter.stringFromDate(date))
                propertiesDictionary.setValue(dateString, forKey: propName)

            } else {
                propertiesDictionary.setValue(propValue, forKey: propName)
            }
        }

        return propertiesDictionary
    }

    public func toJSON() -> NSData! {
        var dictionary = self.toDictionary()
        var err: NSError?
        return NSJSONSerialization.dataWithJSONObject(dictionary, options:NSJSONWritingOptions(0), error: &err)
    }

    public func toJSONString() -> NSString! {
        return NSString(data: self.toJSON(), encoding: NSUTF8StringEncoding)
    }
}

String似乎仅在Optionals为有效值时出现,并且code永远不会出现在对象上(如果它是枚举或Int,除非Int具有默认值。

感谢您为获得课程的所有属性而获得的任何建议,无论他们是什么。

1 个答案:

答案 0 :(得分:3)

我在苹果开发人员论坛上收到了有关此问题的回复:

&#34; class_copyPropertyList仅显示公开给Objective-C运行时的属性。 Objective-C不能表示Swift枚举或非引用类型的选项,因此这些属性不会暴露给Objective-C运行时。&#34;

Source

因此,总而言之,目前无法使用此方法对JSON进行序列化。您可能必须考虑使用其他模式来完成此任务,例如为每个对象提供序列化任务,或者可能使用reflect() method将对象序列化为JSON。