我使用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中的错误吗?
Swift 4注意
let age = aDecoder.decodeObject(forKey: "age") as! Int
在Swift 4中: