[英]save tableview data in swift MVC (Swift)
How save tableview data in swift MVC? 如何在Swift MVC中保存tableview数据?
How can i save data in table on another ViewController? 如何在另一个ViewController上的表中保存数据?
I have a custom class called ToDoItem. 我有一个名为ToDoItem的自定义类。
func save() {
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: ToDoItem.self)
UserDefaults.standard.set(encodedData, forKey: "todosave")
UserDefaults.standard.synchronize()
}
//
func load() {
if let decoded = UserDefaults.standard.object(forKey: "todosave") {
let _ = NSKeyedUnarchiver.unarchiveObject(with: decoded as! Data) as! [ToDoItem]
}
}
I've tried saving it with NSUserDefaults but I get an error. 我尝试使用NSUserDefaults保存它,但出现错误。
ToDoItem.swift ToDoItem.swift
import Foundation
class ToDoItem: NSObject, NSCoding {
var id: String
var image: String
var title: String
var date: Date
init(id: String, image: String, title: String, date: Date) {
self.id = id
self.image = image
self.title = title
self.date = date
}
required convenience init(coder aDecoder: NSCoder) {
let id = aDecoder.decodeObject(forKey: "id") as! String
let image = aDecoder.decodeObject(forKey: "image") as! String
let title = aDecoder.decodeObject(forKey: "title") as! String
let date = aDecoder.decodeObject(forKey: "date") as! Date
self.init(id: id, image: image, title: title, date: date)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: "id")
aCoder.encode(image, forKey: "image")
aCoder.encode(title, forKey: "title")
aCoder.encode(date, forKey: "date")
}
}
I would suggest using Object Mapper and then you can convert the object to JSON, after convert you save it to User Defaults as normally with type Any. 我建议使用Object Mapper,然后将对象转换为JSON,将其转换为通常的Any类型后将其保存为User Defaults。 Then for loading data, you map the data from the User Defaults key that you saved before to your TODOItem. 然后,要加载数据,请将数据从之前保存的“用户默认值”键映射到TODOItem。
The link for ObjectMapper: https://github.com/Hearst-DD/ObjectMapper Also you can use this library for mapping different JSONs to your desired objects ObjectMapper的链接: https : //github.com/Hearst-DD/ObjectMapper也可以使用此库将不同的JSON映射到所需的对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.