kabochappinote

articlesswift
swift codeMemo (NSCoder/Decoder)

swift codeMemo (NSCoder/Decoder)


2021-08-31 12:02:53

⚪︎ NSCoder/Decoder

   //Item class
class Item: Codable { // Codable = Encodable, Decodable
    var title: String = ""
    var done: Bool = false
}



   class ViewController: UIViewController {

    // MARK: - Properties
    private var itemArray = [Item]()
    private let tableView = UITableView()

   // ファイルパス
    private let dataFilePath = FileManager.default.urls(
        for: .documentDirectory, in: .userDomainMask)
        .first?.appendingPathComponent("Items.plist")

   
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()

        loadItems()
        setupViews()
    }

    // MARK: - Helpers
    func setupViews() {
        // setting tableView
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(UITableViewCell.self, 
                           forCellReuseIdentifier: "cellId")

        view.addSubview(tableView)
    }

   // デコードで呼び出し
    // MARK: - Actions
    func loadItems() {
        if let data = try? Data(contentsOf: dataFilePath!) {
            let decoder = PropertyListDecoder()
            do {
                itemArray = try decoder.decode([Item].self, from: data)
            } catch {
                print("DEBUG: Error decoding item array, \(error)")
            }
        }
    }

// エンコードで書き込み
    func saveItems() {
        let encoder = PropertyListEncoder()
        do {
            let data = try encoder.encode(itemArray)
            try data.write(to: dataFilePath!)
        }catch{
            print("DEBUG: Error encoding item array, \(error)")
        }
        self.tableView.reloadData()
    }

   /* setting alert */
    @objc func addTapped() {
        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()
        }
        alert.addTextField { (alertTextField) in
            alertTextField.placeholder = "Create new item"
            textField = alertTextField
        }
        alert.addAction(action)
        present(alert, animated: true, completion: nil)
    }

   // MARK: - TableViewDataSource
extension ViewController: UITableViewDataSource {
    // number of cell
    func tableView(_ tableView: UITableView, 
                   numberOfRowsInSection section: Int) -> Int {
        return itemArray.count
    }
    // setting cell
    func tableView(_ tableView: UITableView, 
                   cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(
            withIdentifier: "cellId", for: indexPath)

        cell.selectionStyle = .none // 選択時の背景色無し
        let item = itemArray[indexPath.row]
        cell.textLabel?.text = item.title
        cell.accessoryType = item.done == true ? .checkmark : .none
        return cell
    }
}


// MARK: - TableViewDelegate
extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, 
                   didSelectRowAt indexPath: IndexPath) {
        let item = itemArray[indexPath.row]
        item.done = !item.done
        saveItems()
    }
}

back