快速从 UserDefaults 保存和检索自定义对象 [英] Swift saving and retrieving custom object from UserDefaults
问题描述
我在 Playground 中使用 Swift 3、Xcode 8.0:
I have this in Playground using Swift 3, Xcode 8.0:
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")
}
}
创建人的数组
create array of Person
let newPerson = Person(name: "Joe", age: 10)
var people = [Person]()
people.append(newPerson)
对数组进行编码
encode the array
let encodedData = NSKeyedArchiver.archivedData(withRootObject: people)
print("encodedData: (encodedData))")
保存到用户默认值
save to userDefaults
let userDefaults: UserDefaults = UserDefaults.standard()
userDefaults.set(encodedData, forKey: "people")
userDefaults.synchronize()
检查
print("saved object: (userDefaults.object(forKey: "people"))")
从 userDefaults 中检索
retreive from 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")
}
只需检查存档数据
just check the archived data
if let myPeopleList = NSKeyedUnarchiver.unarchiveObject(with: encodedData){
print("myPeopleList: (myPeopleList)")
}else{
print("There is an issue")
}
我无法正确地将数据对象保存到 userDefaults,此外,底部的检查创建了错误:
I'm not able to correctly save the data object to userDefaults, and in addition, the check at the bottom creates the error:
致命错误:在展开可选值时意外发现 nil
Fatal error: Unexpectedly found nil while unwrapping an Optional value
检查"行还显示保存的对象为零.这是我对象的 NSCoder 中的错误吗?
The "check" line also shows the saved object is nil. Is this an error in my object's NSCoder?
推荐答案
Swift 4 或更高版本
您可以再次在 Playground 中保存/测试您的值
You can once again save/test your values in a Playground
UserDefaults 需要在实际项目中进行测试.注意:无需强制同步.如果您想在操场上测试编码/解码,您可以使用键控存档器将数据保存到文档目录中的 plist 文件中.您还需要解决班级中的一些问题:
UserDefaults need to be tested in a real project. Note: No need to force synchronize. If you want to test the coding/decoding in a playground you can save the data to a plist file in the document directory using the keyed archiver. You need also to fix some issues in your class:
class Person: NSObject, NSCoding {
let name: String
let age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
required init(coder decoder: NSCoder) {
self.name = decoder.decodeObject(forKey: "name") as? String ?? ""
self.age = decoder.decodeInteger(forKey: "age")
}
func encode(with coder: NSCoder) {
coder.encode(name, forKey: "name")
coder.encode(age, forKey: "age")
}
}
测试:
Testing:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
do {
// setting a value for a key
let newPerson = Person(name: "Joe", age: 10)
var people = [Person]()
people.append(newPerson)
let encodedData = try NSKeyedArchiver.archivedData(withRootObject: people, requiringSecureCoding: false)
UserDefaults.standard.set(encodedData, forKey: "people")
// retrieving a value for a key
if let data = UserDefaults.standard.data(forKey: "people"),
let myPeopleList = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? [Person] {
myPeopleList.forEach({print($0.name, $0.age)}) // Joe 10
}
} catch {
print(error)
}
}
}
这篇关于快速从 UserDefaults 保存和检索自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!