为什么NSUserDefaults的检索失败了我的自定义对象?

时间:2016-08-25 08:19:42

标签: swift nsuserdefaults nscoding nskeyedarchiver

我有一个类PredicPair,它继承自NSCodingNSObject

class PredicPair: NSObject, NSCoding {

    var weight : Float
    var prediction : String

    init(weight: Float, prediction: String) {
        self.weight = weight
        self.prediction = prediction

        super.init()
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(weight, forKey: "weight")
        aCoder.encode(prediction, forKey: "prediction")
    }

    required convenience init(coder aDecoder: NSCoder) {
        let unarchivedWeight = aDecoder.decodeObject(forKey: "weight") as! Float
        let unarchivedPrediction = aDecoder.decodeObject(forKey: "prediction") as! String

        self.init(weight: unarchivedWeight, prediction: unarchivedPrediction)
    }

    class func saveToUserDefaults(pairs: [PredicPair]) {
        let dataBlob = NSKeyedArchiver.archivedData(withRootObject: pairs)
        UserDefaults.standard.set(dataBlob, forKey: "test")
        UserDefaults.standard.synchronize()
    }

    class func loadFromUserDefaults() -> [PredicPair]? {
        guard let decodedNSDataBlob = UserDefaults.standard.object(forKey: "test") as? NSData,
            let loadedFromUserDefault = NSKeyedUnarchiver.unarchiveObject(with: decodedNSDataBlob as Data) as? [PredicPair]
            else {
                return nil
        }

        return loadedFromUserDefault
    }
}

我试图在UserDefaults中存储一个类的数组并检索它,但后者总是返回nil。有什么理由吗?

let predicPair1 = PredicPair(weight: 0, prediction: "there")
let predicPair2 = PredicPair(weight: 1, prediction: "hello")

let array = [predicPair1, predicPair2]

PredicPair.saveToUserDefaults(pairs: array)
if let retreivedArray = PredicPair.loadFromUserDefaults() {
    print("loaded \(retreivedArray.count) players from NSUserDefaults")
} else {
    print("failed")
}

我还尝试使用NSKeyedArchiver保存到文件,但检索也失败了。

0 个答案:

没有答案