2024-12-10
结果:保存在用户的Documents
文件夹下。
因为数据的样式是系统不认识的,即不是基本数据类型
,比如struct或者class。想象成把音乐做成黑胶唱片,就是encode的过程。而用播放设备播放音乐,就是把黑胶唱片还原成音乐,是decode的过程。
let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("Items.plist")
import Foundation
class Item: Codable{
var title: String = ""
var done: Bool = false
}
func saveItems(){
let encoder = PropertyListEncoder()
do{
let data = try encoder.encode(itemArray)
try data.write(to: dataFilePath!)
} catch {
print("Error encoding item array, \(error)")
}
}
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Add New Todoey Item", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Add Item", style: .default)
{ (action) in
let newItem = Item()
newItem.title = textField.text!
self.itemArray.append(newItem)
self.saveItems()
//重新渲染tableView
self.tableView.reloadData()
}
alert.addTextField { (alertTextField) in
alertTextField.placeholder = "Create New Item"
textField = alertTextField
}
alert.addAction(action)
present(alert, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
print(dataFilePath!)
loadItems()
}
func loadItems(){
if let data = try? Data(contentsOf: dataFilePath!) {
let decoder = PropertyListDecoder()
do{
itemArray = try decoder.decode([Item].self, from: data)
} catch {
print("Error decoding item array, \(error)")
}
}
}