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

时间:2018-07-22 16:25:22

标签: swift core-data tableview reorderlist

因此,当我重新排序行时,我有了tableview,它会更新tableview和所有内容,但不会保存到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不会。 t保存新的行位置。由于某种原因,它正在运行我的catch块,因为我收到错误无法移动行。

这是控制台中的一些错误。

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

先谢谢了。

1 个答案:

答案 0 :(得分:1)

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

就像“ 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)")
    }
}

您可以通过一百万种不同的方式来改善此想法(这总是很受欢迎),但这是解决方案的教学示例。

我希望它可以帮助某个人!