NSKeyedUnarchiver.unarchiveObject不起作用

时间:2017-03-05 12:29:29

标签: ios swift nscoding

调用NSKeyedArchiver.archiveRootObject但是getter返回变量' a'没有。这让我烦恼。

任何人都能看到问题所在吗?

let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("Information.ab")

var info: Information? {
        get {
            let a = NSKeyedUnarchiver.unarchiveObject(withFile: url.absoluteString) as? Information
            return a
        }
        set {
            if info != newValue && newValue != nil {
                NSKeyedArchiver.archiveRootObject(newValue as Any, toFile: url.absoluteString)
            }
        }
    }

class Information: RecordModel {

    let rules: CKAsset
    let aboutUs: String
    let terms: String
    let privacyPolicy: String

    override init(record: CKRecord) {
        rules = record["rules"] as! CKAsset
        aboutUs = record["aboutUs"] as! String
        terms = record["terms"] as! String
        privacyPolicy = record["privacyPolicy"] as! String
        super.init(record: record)
    }

}

class RecordModel: NSObject, NSCoding {

    let record: CKRecord

    init(record: CKRecord) {
        self.record = record
    }

    required convenience init?(coder aDecoder: NSCoder) {
        let record = aDecoder.decodeObject(forKey: "keyRecord") as! CKRecord
        self.init(record: record)
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(record, forKey: "keyRecord")
    }

    override func isEqual(_ object: Any?) -> Bool {
        if let rhs = object as? Information {
            return record.recordID == rhs.record.recordID
        }
        return false
    }

    override var hash: Int {
        return record.recordID.hashValue
    }

}

1 个答案:

答案 0 :(得分:2)

unarchiveObject(withFilearchiveRootObject(_:toFile期望文件路径没有file://方案,因此在两种情况下

url.path

而不是 url.absoluteString