如何将重新排序的Tableview单元格保存到核心数据 [英] How To Save Re-Ordered Tableview Cells To Core Data
问题描述
所以当我重新排序行时,我有了我的tableview
,它会更新tableview
以及所有内容,但不会保存到core data
中.
So I have my tableview
when I re-order my rows it updates the tableview
and everything but it isn't saving to core data
.
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let movedCampSites = itemName[sourceIndexPath.item]
itemName.remove(at: sourceIndexPath.item)
itemName.insert(movedCampSites, at: destinationIndexPath.item)
context.delete(itemName[sourceIndexPath.row])
context.insert(itemName[destinationIndexPath.row])
do
{
try context.save()
}
catch
{
print("Could not move rows")
}
}
一切正常,直到context.insert(itemName[destinationIndexPath.row])
,例如,如果我注释掉并运行它,它将移动行并删除该行并保存到core data
,但是context.insert
不会保存新的行位置.由于某种原因,它正在运行我的catch块,因为我收到错误消息无法移动行".
Everything works up till context.insert(itemName[destinationIndexPath.row])
for example if I comment that out and run it, it will move the rows and delete the row and save to core data
, but the context.insert
doesn't save the new row position. For some reason it is running my catch block as I am getting the error Could not move rows.
这是控制台中的一些错误.
Here is some of the error that is in the console.
2018-07-22 09:27:01.884925-0700搜索栏核心数据[67957:5383630] [错误]错误:(1555)唯一约束失败:ZTITLE.Z_PK CoreData:错误:(1555)唯一约束失败:ZTITLE.Z_PK 无法移动行
2018-07-22 09:27:01.884925-0700 Search Bar Core Data[67957:5383630] [error] error: (1555) UNIQUE constraint failed: ZTITLE.Z_PK CoreData: error: (1555) UNIQUE constraint failed: ZTITLE.Z_PK Could not move rows
先谢谢了.
推荐答案
这是我对这个问题的看法:
Here is my take on this issue:
就像"vadian"说的那样,当您创建对象时,您会为附加到核心数据的数组添加一个属性,就像这样,
Like 'vadian' said, when you create an object you add a property for the array that appends to the Core Data, like this,
var itemsArray: [NSManagedObject] = []
save(sortOrder: itemsArray.count, item: itemTextField.text!) //Calling the save method wherever you need to, catching for example a UITextField user input
private func save(sortOrder: Int, item: String) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let context = appDelegate.persistentContainer.viewContext
guard let entity = NSEntityDescription.entity(forEntityName: "CoreDataBaseName", in: context) else { return }
let itemManagedObject = NSManagedObject(entity: entity, insertInto: context)
itemManagedObject.setValue(sortOrder, forKeyPath: "sortOrder")
itemManagedObject.setValue(item, forKeyPath: "item")
do {
try context.save()
itemsArray.append(itemManagedObject)
} catch let error as NSError {
print("Could not save item to Core Data: \(error)")
}
}
然后我们进入tableView的moveRowAt方法,
Then we come to the tableView's moveRowAt method,
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let context = appDelegate.persistentContainer.viewContext
let movedItem = itemsArray[sourceIndexPath.row]
itemsArray.remove(at: sourceIndexPath.row)
itemsArray.insert(movedItem, at: destinationIndexPath.row)
//This 'for-in loop' is at the heart of the solution
for (i, item) in itemsArray.enumerated() {
item.setValue(i, forKey: "sortOrder")
}
do {
try context.save()
} catch let error as NSError {
print("Could not save/persist Core Data items in moveRowAt: \(error)")
}
}
...在所有操作的最后,我们都使用
... And at the end of everything we fetch the rearranged order with,
private func fetch() {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let context = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "CoreDataBaseName")
let sortDescriptor = NSSortDescriptor(key: "sortOrder", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
do {
itemsArray = try context.fetch(fetchRequest)
} catch let error as NSError {
print("Could not fetch Core Data entities: \(error)")
}
}
您可以通过一百万种不同的方式来改进此想法(这总是很受欢迎),但这是解决方案的教学示例.
There's a million different ways that you can improve this idea (which is always welcome), but this is a pedagogical example of a solution.
我希望它可以帮助某个人!
I hope it can help somebody out there!
这篇关于如何将重新排序的Tableview单元格保存到核心数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!