我正在尝试在UserDefaults中存储一个数组但却找不到解决方案。我有一个py34
和struct
设置,用于在数组中存储“name”和“description”。代码如下......
func
将数据存储在UserDefaults中的最佳方法是什么,并在重新启动后将信息添加到struct task {
var name = "Untitled"
var description = "No description available"
}
var tasks = [task]()
func addTask(name: String, description: String) {
tasks.append(task(name: name, description: description))
}
和cell.textLabel?.text
?
答案 0 :(得分:0)
以Swift惯例命名以大写字母开头的结构。您需要创建一个类,使其符合NSCoding并使用KeyedArchiever来保存对象数据
class Task: NSObject, NSCoding {
let name: String
let desc: String
required init(name: String, desc: String) {
self.name = name
self.desc = desc
}
func encode(with coder: NSCoder) {
coder.encode(name, forKey: "name")
coder.encode(desc, forKey: "desc")
}
required init(coder decoder: NSCoder) {
self.name = decoder.decodeObject(forKey: "name") as? String ?? ""
self.desc = decoder.decodeObject(forKey: "desc") as? String ?? ""
}
}
测试
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var descField: UITextField!
@IBOutlet weak var tableView: UITableView!
var tasks: [Task] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
if let data = UserDefaults.standard.data(forKey: "tasks") {
tasks = NSKeyedUnarchiver.unarchiveObject(with: data) as? [Task] ?? []
tableView.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func addTask(_ sender: UIButton) {
guard let name = nameField.text, let desc = descField.text else { return }
tasks.append(Task(name: name, desc: desc))
UserDefaults.standard.set(NSKeyedArchiver.archivedData(withRootObject: tasks) , forKey: "tasks")
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellID")!
cell.textLabel?.text = tasks[indexPath.row].name + " - " + tasks[indexPath.row].desc
return cell
}
}