我已经搜索了几天的问题答案,用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
}
}
我很乐意提供帮助:)
答案 0 :(得分:1)
您无法将[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
,您不应该在代码中手动调用它:)
答案 1 :(得分:1)
正如@donnywals在他的回答中所说,您不能直接将自定义对象写入UserDefaults
。只有一小部分数据类型(我记得的是Date
,Array
,Dictionary
,Int
,Float
,Double
,可以将称为““属性列表对象”的Data
,String
。)写入UserDefaults
或属性列表文件。
在我看来,您正在使用Core Data,那么为什么要尝试将对象数组写入UserDefaults?这是对UserDefaults
的滥用,这是CoreData的目的,所以为什么不将数据保存到Core Data中呢?