下午好!使用NSCoding在Swift 3中编码和解码函数如何工作?
任何人都可以帮助我理解如何使用NSCoding
在Swift中保存数据?我是这门语言的初学者,目前我正在看一些关于如何使用表格视图的教程(创建单元格,保存数据等)。
以下代码创建一个UITableView
,我可以在其中添加雇员的名字和姓氏。然而,我不明白这些编码和解码函数是如何工作的,因为它只被分配了一个名字和一个关键字(这是我所理解的)。我的意思是,因为它是一群员工,而且这些功能足够智能,可以为所有员工的姓名和姓氏提供相同的密钥,然后检索数据?
的ViewController类:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var data = [Employee]()
@IBOutlet weak var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
loadData()
}
var filePath: String {
let manager = FileManager.default
let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first
return url!.appendingPathComponent("Data").path
}
private func loadData(){ //Decode
if let ourData = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? [Employee] {
data = ourData
}
}
private func saveData(employee: Employee){ //Encode
self.data.append(employee)
NSKeyedArchiver.archiveRootObject(data, toFile: filePath)
}
func numberOfSections(...)
func tableView(...)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//Could be UITableViewCell(), but for a better performance we use this reusable form below:
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
//"indexPath" will return the information based on the number of rows we have. The number of rows in this case is "data.count"
cell.textLabel?.text = data[indexPath.row].Name
cell.detailTextLabel?.text = data[indexPath.row].LastName
return cell
}
@IBAction func addEmployee(_ sender: AnyObject) {
let alert = UIAlertController(title: "Add New Employee", message: "Enter Employee's name", preferredStyle: .alert)
let saveButon = UIAlertAction(title: "Save", style: .default){
(alertAction: UIAlertAction) in
let employeeName = alert.textFields?[0].text!
let employeeLastName = alert.textFields?[1].text!
let newEmployee = Employee(name: employeeName!, lastName: employeeLastName!)
self.saveData(employee: newEmployee)
self.myTableView.reloadData()
}
let cancelButton = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alert.addTextField(configurationHandler: nil)
alert.addTextField(configurationHandler: nil)
alert.addAction(saveButon)
alert.addAction(cancelButton)
self.present(alert, animated: true, completion: nil)
}
}
Employee类图片:
我希望你明白我的问题,否则让我知道。非常感谢你!
它序列化和反序列化您的对象模型,以便它可以存储到磁盘。 – Steve