2017-02-27 51 views
1

下午好!使用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类图片:

code image

我希望你明白我的问题,否则让我知道。非常感谢你!

+0

它序列化和反序列化您的对象模型,以便它可以存储到磁盘。 – Steve

回答

0

关键是编码器用来序列化和反序列化你的类的属性。你可以给他们任何字符串值。如果你喜欢而不是“名字”,你可以调用firstName属性键“firstName”,但是他们必须匹配你编码和解码对象时的值。如果他们不这样做,你不会得到你期望的价值。课程必须与正在解码和编码的课程相匹配,以防将来改变此课程,否则您将遇到崩溃。数据将在启动之间保持不变。数据存储在应用程序文件目录中。这是一个使用上述确切代码的项目的链接。你可以亲眼看到它会在启动之间持续。 https://www.dropbox.com/s/zuxd1kt3brkxtgi/Archiving.zip?dl=0