首页 > 解决方案 > 在 TableView 中重新排序行后将对象保存在 UserDefaults 中

问题描述

我已经搜索了几天来回答如何在使用 Swift 重新排序 TableView 后保存对象?我在互联网上找到了许多教程,展示了如何重新排序以及如何使用数组保存它。

无论我尝试什么,我都不会出去。我从实体中提取数据。但是当我尝试在 userdefaults 中保存排序时,我收到以下错误:

[用户默认值] 尝试设置非属性列表对象

我不知道为什么我没有存储重新排序。

这是我现在的代码。我错了什么?
请问您能帮我解决问题吗?非常感谢。


import UIKit
import CoreData

class hondenTableViewController: UITableViewController {

    var honden = [Hond]() // legen array aanmaken
    var dateFormatter = DateFormatter()

    let store = UserDefaults(suiteName: "MultiSelectTable")
    var opgeslagenHonden = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        if let defaults = self.store?.array(forKey: "hondjes")  {
            self. opgeslagenHonden = defaults
        } 


        self.navigationItem.leftBarButtonItem = self.editButtonItem

        // Nederlands opgebouwde datum op geven
        dateFormatter.dateFormat = "E d MMM y"
        self.tableView.reloadData()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext

        let fetchReqeust = Hond.fetchRequest() as NSFetchRequest
        do {
            honden = try context.fetch(fetchReqeust)
        } catch let error {
            print("Ophalen mislukt door error\(error)")
        }

        tableView.reloadData()

    }
    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return honden.count

    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "hondenCellIdentifier", for: indexPath)
        let hond = honden[indexPath.row]

        cell.textLabel?.text = hond.naam

        if let date = hond.geboortedatum as Date? {
            let formatter = DateFormatter()
            formatter.dateFormat = "dd/MM/yyyy"

            cell.detailTextLabel?.text = "Geboren op : " + dateFormatter.string(from: date) + " = " + helper.berekenLeeftijd(formatter.string(from: date) + " oud.")

        } else {
            cell.detailTextLabel?.text = "Geboortedatum onbekend."
        }

        return cell
    }

    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }

    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        if honden.count > indexPath.row {

            let hond = honden[indexPath.row]

            let appDelegate = UIApplication.shared.delegate as! AppDelegate
            let context = appDelegate.persistentContainer.viewContext

            context.delete(hond)
            honden.remove(at: indexPath.row)

            do {
                try context.save()
            } catch let error {
                print("Kan niet verwijderen door: \(error).")
            }

            tableView.deleteRows(at: [indexPath], with: .fade)
        }
    }

    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        let movedObject = self.honden[sourceIndexPath.row]
        honden.remove(at: sourceIndexPath.row)
        honden.insert(movedObject, at: destinationIndexPath.row)

        let defaults = UserDefaults.standard
        defaults.set(honden, forKey: "hondjes")
        defaults.synchronize()
        //NSLog("%@", "\(sourceIndexPath.row) => \(destinationIndexPath.row) \(honden)")
    }

    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }

}

我会很高兴得到帮助:)

标签: iosswiftuitableview

解决方案


您不能将类型的对象[Hond]写入UserDefaults. 您拥有的一种选择是在写入数组之前使其Hond符合Codable数组并将其编码为Data使用,并在检索JSONEncoder数据[Hond]时将其解码:

let encoder = JSONEncoder()
let data = try? encoder.encode(honden)
defaults.set(data, forKey: "hondjes")

// and

let loadedData = defaults.data(forKey: "hondjes")!
let decoder = JSONDecoder()
let honden = try? decoder.decode([Hond].self, from: loadedData)

另外,检查文档synchronize,你不应该在你的代码中手动调用它:)


推荐阅读