[英]moveRowAtIndexPath using CoreData in Swift 2
閱讀超過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)")
}
}
}
我想我想通了@AdrianB,因為我不知道orderedSet.exchangeObjectAtIndex
方法
就我而言,以下實現有效
let preferiti = calcoloVC.utenteCorrente.preferiti.mutableCopy() as! NSMutableOrderedSet
preferiti.exchangeObjectAtIndex(fromIndexPath.row, withObjectAtIndex: toIndexPath.row)
calcoloVC.utenteCorrente.preferiti = preferiti.copy() as! NSOrderedSet
var error: NSError?
do {
try managedContext.save()
} catch let error1 as NSError {
error = error1
print("Could not save: \(error)")
}
現在,我需要弄清楚在哪里寫saveManagedObjectContext而不是每次都重寫它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.