Сохранить переупорядоченные ячейки с помощью CoreData - PullRequest
0 голосов
/ 05 апреля 2020

enter image description here Я искал ответ везде, но не могу найти один ...

После изменения порядка ячеек tableView я хотел бы сохранить эти изменения с помощью CoreData , Как мне сделать это, как можно проще?

Вот мой код:

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        //Set new order
        let itemMove = taskArray[sourceIndexPath.row] //Get the item that we just moved
        taskArray.remove(at: sourceIndexPath.row) // Remove the item from the array
        taskArray.insert(itemMove, at: destinationIndexPath.row) //Re-insert back into array

        tableView.reloadData()
    }

enter image description here

Ответы [ 2 ]

1 голос
/ 05 апреля 2020
  1. Во-первых, так должна выглядеть ваша сущность.

enter image description here

Теперь изначально нет сохраненных данных. Каждый раз, когда вы создаете новую задачу, сначала извлекайте все данные и сохраняйте их в tasksArray, сортируйте их по индексу, а затем добавляйте новую задачу в массив и сохраняйте новую задачу в основных данных.

// Fetch data here and sort the array.

tasksArray = tasksArray.sorted { $0.index < $1.index }

// Create new Task.

let newTask = Task(context: (UIApplication.shared.delegate as! 
AppDelegate).persistentContainer.viewContext)

newTask.addInfo = "Info"
newTask.nameOfTask = "Some Task"

// Append new task.

tasksArray.append(newTask) 
newTask.index = Int64(tasksArray.endIndex - 1)

// Save new task to Core Data here.

(UIApplication.shared.delegate as! AppDelegate).saveContext()

Теперь все задачи имеют индекс (0,1..так на). Вы можете проверить это, выбирая задачи. Теперь при каждом перемещении строк выполните следующее:

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: 
IndexPath, 
to destinationIndexPath: IndexPath) {

let itemMove = taskArray[sourceIndexPath.row] 

taskArray.remove(at: sourceIndexPath.row) 

taskArray.insert(itemMove, at: destinationIndexPath.row) 

}

Теперь проблема в том, что все индексы изменились. Решение состоит в том, чтобы обновить все значения, когда строки закончат перемещение.

for (index,task) in tasksArray.enumerated(){
     task.index = Int64(index)
}

(UIApplication.shared.delegate as! AppDelegate).saveContext()

// Fetch data here again and save it to tasksArray.

tableView.reloadData()

Пожалуйста, проверьте это работает, так как у меня не было времени, чтобы проверить это самостоятельно. Надеюсь, что это решит вашу проблему.

1 голос
/ 05 апреля 2020

Вам необходимо переиндексировать записи после перемещения строк

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        //Set new order
        let itemMove = taskArray[sourceIndexPath.row] //Get the item that we just moved
        taskArray.remove(at: sourceIndexPath.row) // Remove the item from the array
        taskArray.insert(itemMove, at: destinationIndexPath.row) //Re-insert back into array

        tableView.reloadData()
        for (index, element) in taskArray.enumerated() {
            element.index = Int16(index)
        }
        do { try context.save() }
        catch { print(error) }
    }

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

let request = Task.fetchRequest()
request.sortDescriptors = [NSSortDescriptor(key: "index", ascending: true)]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...