阅读超过10篇用Obj-C和Swift撰写的文章之后。
我仍然不知道如何使用CoreData重新排列列表中的行。

由于我知道如何添加新对象以及如何删除对象,因此我尝试将两者合并在一起,并且moveRowAtIndexPath方法变为

let prefToMove = mainVC.user.prefs[fromIndexPath.row] as! Pref

var prefs = mainVC.user.prefs.mutableCopy() as! NSMutableOrderedSet
prefs.addObject(prefToMove)

mainVC.user.prefs = prefs.copy() as! NSOrderedSet

// managed object context saving
var error: NSError?
do {
  try managedContext!.save()
} catch let error1 as NSError {
  error = error1
  print("Could not save: \(error)")
}
tableView.insertRowsAtIndexPaths([toIndexPath], withRowAnimation: .None)

prefs = mainVC.user.prefs.mutableCopy() as! NSMutableOrderedSet
prefs.removeObjectAtIndex(fromIndexPath.row)
mainVC.user.prefs = prefs.copy() as! NSOrderedSet

managedContext.deleteObject(prefToMove)

// managed object context saving
do {
  try managedContext.save()
} catch let error1 as NSError {
  error = error1
  print("Could not save: \(error)")
}

// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([fromIndexPath], withRowAnimation: .None)

tableView.reloadData()

但是,它不起作用。删除部分有效,但插入失败。
有人可以给我任何帮助吗?

最佳答案

在四处移动行时并没有真正删除或插入任何内容。无论您的数据集是什么,请尝试exchangeObjectAtIndex

override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    let orderedSet: NSMutableOrderedSet = (routineToReorder?.mutableOrderedSetValueForKey("yourKeyValue"))!

    orderedSet.exchangeObjectAtIndex(fromIndexPath.row, withObjectAtIndex: toIndexPath.row)

    saveManagedObjectContext() // I have a standalone method for this that I call from several places
}

更新

这是saveManagedObjectContext()的样子:
func saveManagedObjectContext() {
    if self.managedObjectContext.hasChanges {
        do {
            try managedObjectContext.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nserror = error as NSError
            NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

10-07 21:33