Как сохранить переупорядоченные ячейки табличного представления в базовые данные

Итак, у меня есть 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 не сохраняет новую позицию строки По какой-то причине он запускает мой блок catch, поскольку я получаю сообщение об ошибке. Не удалось переместить строки.

Вот некоторые из ошибок, которые есть в консоли.

2018-07-22 09: 27: 01.884925-0700 Базовые данные панели поиска [67957:5383630] ошибка [ошибка]: (1555) Сбой уникального ограничения: ZTITLE.Z_PK CoreData: ошибка: (1555) Сбой уникального ограничения: ZTITLE.Z_PK Не удалось переместить строки

Заранее спасибо.

0 ответов

Вот мой взгляд на этот вопрос:

Как сказал vadian, когда вы создаете объект, вы добавляете свойство для массива, который присоединяется к Core Data, например,

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)")
    }
}

Затем мы переходим к методу moveRowAt tableView,

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)")
    }
}

Есть миллион различных способов улучшить эту идею (что всегда приветствуется), но это педагогический пример решения.

Надеюсь, это поможет кому-нибудь!

Другие вопросы по тегам