Swift 3从userDefaults保存和检索自定义对象

问题描述 投票:61回答:4

我使用Swift 3,Xcode 8.0在Playground中拥有此功能:

import Foundation
class Person: NSObject, NSCoding {
    var name: String
    var age: Int
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
    required convenience init(coder aDecoder: NSCoder) {
        let name = aDecoder.decodeObject(forKey: "name") as! String
        let age = aDecoder.decodeObject(forKey: "age") as! Int
        self.init(
            name: name,
            age: age
        )
    }
    func encode(with aCoder: NSCoder) {
        aCoder.encode(name, forKey: "name")
        aCoder.encode(age, forKey: "age")
    }
}

创建人数组

let newPerson = Person(name: "Joe", age: 10)
var people = [Person]()
people.append(newPerson)

编码数组

let encodedData = NSKeyedArchiver.archivedData(withRootObject: people)
print("encodedData: \(encodedData))")

保存到userDefaults

let userDefaults: UserDefaults = UserDefaults.standard()
userDefaults.set(encodedData, forKey: "people")
userDefaults.synchronize()

print("saved object: \(userDefaults.object(forKey: "people"))")


从userDefaults检索

if let data = userDefaults.object(forKey: "people") { let myPeopleList = NSKeyedUnarchiver.unarchiveObject(with: data as! Data) print("myPeopleList: \(myPeopleList)") }else{ print("There is an issue") }


仅检查存档数据

if let myPeopleList = NSKeyedUnarchiver.unarchiveObject(with: encodedData){ print("myPeopleList: \(myPeopleList)") }else{ print("There is an issue") }

我无法将数据对象正确保存为userDefaults,此外,底部的检查还会产生错误“严重错误:在展开可选值时意外发现nil”。 “检查”行还显示已保存的对象为nil。这是我对象的NSCoder中的错误吗?
ios swift xcode swift3 nscoding
4个回答
90
投票

Swift 4注意


49
投票
let age = aDecoder.decodeObject(forKey: "age") as! Int

11
投票
尝试一下:

6
投票

在Swift 4中:

© www.soinside.com 2019 - 2024. All rights reserved.