Swift 如何将重新排序的Tableview单元格保存到核心数据

Swift 如何将重新排序的Tableview单元格保存到核心数据,swift,core-data,tableview,reorderlist,Swift,Core Data,Tableview,Reorderlist,因此,我有我的tableview当我重新排序行时,它会更新tableview和所有内容,但不会保存到核心数据 func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { let appDelegate = UIApplication.shared.delegate as! AppDelegate let

因此,我有我的
tableview
当我重新排序行时,它会更新
tableview
和所有内容,但不会保存到
核心数据

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[destinationindepath.row])
之前,一切都正常运行。例如,如果我将其注释掉并运行它,它将移动行并删除行并保存到
核心数据,但
context.insert
不会保存新行位置。由于某些原因,它正在运行catch块,因为我得到了无法移动行的错误

下面是控制台中的一些错误

2018-07-22 09:27:01.884925-0700搜索栏核心数据[67957:5383630][错误]错误:(1555)唯一约束失败:ZTITLE.Z_PK CoreData:错误:(1555)唯一约束失败:ZTITLE.Z_PK 无法移动行


提前谢谢

以下是我对这个问题的看法:

就像“vadian”所说的,当您创建一个对象时,您为附加到核心数据的数组添加了一个属性,如下所示

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方法

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)")
    }
}
。。。在一切结束时,我们用

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)")
    }
}
private func fetch(){
让appDelegate=UIApplication.shared.delegate作为?appDelegate else{return}
让上下文=appDelegate.persistentContainer.viewContext
let fetchRequest=NSFetchRequest(entityName:“CoreDataBaseName”)
让sortDescriptor=NSSortDescriptor(键:“sortOrder”,升序:true)
fetchRequest.sortDescriptors=[sortDescriptor]
做{
itemsArray=try context.fetch(fetchRequest)
}将let错误捕获为NSError{
打印(“无法获取核心数据实体:\(错误)”)
}
}
有一百万种不同的方法可以改进这个想法(这总是受欢迎的),但这是一个解决方案的教学示例


我希望它能帮助别人

从核心数据的角度来看,没有区别,因为它将对象无序保存。好的,那么我如何才能更改它,使其正常工作?如果您需要特定的顺序,请使用或添加可以按此顺序排序的核心数据属性(例如Int32索引),如果此答案正确=d,我希望使用绿色复选标记