【问题标题】:Get Property List of Swift Class获取 Swift 类的属性列表
【发布时间】:2014-09-02 20:55:41
【问题描述】:

我正在尝试获取 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)
    }
}

字符串似乎只在 Optionals 是有效值时出现,而 code 永远不会出现在对象上,如果它是枚举或 Int,除非 Int 具有默认值。

感谢任何关于获取类的所有属性的建议,无论它们是什么。

【问题讨论】:

  • 有没有人知道从哪里开始,或者是否有人需要更多信息?
  • 我有这个完全相同的问题,使用相同的要点。这个问题已经一个月了。任何更新?我一直在摇头,认为必须有一种直接的方法来序列化一个 swift 类,但我还没有找到一种可以端到端工作的方法。

标签: serialization enums swift


【解决方案1】:

我在苹果开发者论坛上收到了关于这个问题的回复:

"class_copyPropertyList 只显示暴露给 Objective-C 运行时的属性。Objective-C 不能表示 Swift 枚举或非引用类型的可选项,因此这些属性不会暴露给 Objective-C 运行时。"

Source

因此,总而言之,目前无法使用这种方法序列化为 JSON。您可能需要考虑使用其他模式来完成此操作,例如将序列化任务分配给每个对象,或者可能使用 reflect() method 将对象序列化为 JSON。

【讨论】:

    猜你喜欢
    • 2021-03-26
    • 2014-09-10
    • 2013-11-06
    • 2010-10-18
    • 2021-01-08
    • 2020-02-29
    • 2019-01-12
    • 1970-01-01
    相关资源
    最近更新 更多