ios - 在 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
}
}
我会很高兴得到帮助:)
解决方案
您不能将类型的对象[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
,你不应该在你的代码中手动调用它:)
推荐阅读
- android - 如何使用 Android Java Camera View 模块创建自定义 React Native 组件?
- html - 如何使导航栏的每个选项卡均等地适合屏幕
- flutter - 我对颤振中的“awesome_dialog”包有问题
- javascript - 选择多个过滤器,仅显示具有共同特征的标记
- excel - 在多个工作表中使用通用下拉菜单来更改单个单元格
- google-app-engine - 具有 GCP 免费套餐的 Google Flex App Engine 实例,可以吗?
- java - 当我的整数数组是多模式且没有模式时,我的 Java 查找模式的方法失败
- ios - 动态调整集合视图单元格的大小
- html - 如何在 HTML/CSS 中的图像背景上为内容创建一个白框?
- python - Django 模型:访问表之间的多级链接