おはよう!NSCodingを使用してSwift 3でエンコードおよびデコード機能がどのように機能しますか?
SwiftでNSCoding
を使用してデータを保存する方法を教えてもらえますか?私はこの言語の初心者です。現在、テーブルビュー(セルの作成、データの保存など)の操作方法に関するチュートリアルを見ています。
以下のコードはUITableView
を作成しています。従業員の姓と名を追加するだけです。しかし、私はこれらのエンコードとデコード機能がどのように機能するのか理解できません。なぜなら、最初の名前に1つのキー、最後に名前に1つのキーしか割り当てられていないからです。つまり、それは従業員の配列であり、すべての従業員の名字に同じキーを与えてからデータを取得するのに十分なインテリジェントな機能なのですか?
の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