重新排序行并将更新保存到核心数据

时间:2016-03-23 13:10:27

标签: ios swift uitableview core-data

我从来没有想到要重新排序表并将新订单保存到核心数据(也许我会过度思考它)。下面的代码如下所示:"更新后现有部分中包含的行数必须等于更新前该部分中包含的行数。"

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

    initializeFetchedResultsController()

    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let context2: NSManagedObjectContext = appDel.managedObjectContext
    let request2 = NSFetchRequest(entityName: "Activities")
    let activityOrderSort = NSSortDescriptor(key: "activityOrder", ascending: true)
    request2.sortDescriptors = [activityOrderSort]

    let predicate = NSPredicate(format: "date == %@", date)
    request2.predicate = predicate

    var fetchResults2: [NSManagedObject]

    do {
        try fetchResults2 = (appDel.managedObjectContext.executeFetchRequest(request2) as! [NSManagedObject])

        if fromIndexPath.row > toIndexPath.row {
            for i in toIndexPath.row..<fromIndexPath.row {
                fetchResults2[i].setValue(i+1, forKey: "activityOrder")
            }
            fetchResults2[fromIndexPath.row].setValue(toIndexPath.row, forKey: "activityOrder")
        }
        if fromIndexPath.row < toIndexPath.row {
            for i in fromIndexPath.row + 1...toIndexPath.row {
                fetchResults2[i].setValue(i-1, forKey: "activityOrder")
            }
            fetchResults2[fromIndexPath.row].setValue(toIndexPath.row, forKey: "activityOrder")
        }

    } catch let error as NSError {
        print("Error: \(error.localizedDescription)")
    }

    do {
        try appDel.managedObjectContext.save()
    } catch let error as NSError {
        print("Saving error: \(error.localizedDescription)")
    }

    initializeFetchedResultsController()

}

这是initializeFetchedResultsController()代码供参考:

func initializeFetchedResultsController() {

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    context = appDelegate.managedObjectContext

    let fetchRequest = NSFetchRequest(entityName: "Activities")
    let orderSort = NSSortDescriptor(key: "activityOrder", ascending: true)
    fetchRequest.sortDescriptors = [orderSort]

    let predicate = NSPredicate(format: "date == %@", date)
    fetchRequest.predicate = predicate

    fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
        managedObjectContext: self.context,
        sectionNameKeyPath: nil,
        cacheName: nil)

    fetchedResultsController.delegate = self

    do {
        try fetchedResultsController.performFetch()
    } catch let error as NSError {
        print("Error: \(error.localizedDescription)")
    }
} 

我试图尽可能多地从上一篇文章的回答中提取:Save new order to core data after the using the tableView:moveRowAtIndexPath:toIndexPath: method。此外,我设置了canEditRowAtIndexPath函数,它似乎正常运行。有什么明显的东西让我搞砸了提供的代码吗?有更简单的解决方案吗?感谢您的支持。

0 个答案:

没有答案