在Swift中自动重新排序Core Data

时间:2015-01-30 19:58:30

标签: xcode swift

我想在“编辑模式”下移动单元格时重新排序我的核心数据列表。对于Obj-c这个领域似乎有一些有用的讨论(见下面的链接),但我在Swift中找不到任何东西。

有没有人遇到过Swift的相关文档?或者有人愿意将obj-c代码翻译成Swift吗?谢谢!

对象链接:

How can I maintain display order in UITableView using Core Data?

How to implement re-ordering of CoreData records?

1 个答案:

答案 0 :(得分:2)

这是我做的一个很好的方式。它还会检查目的地是否包含任何数据,您还可以跨部门移动。 isMoving将禁止代表开火。您还需要实体的sortorder属性。

private func indexIsOutOfRange(indexPath:NSIndexPath) -> Bool {
    if indexPath.section > self.fetchedResultsController.sections!.count - 1 {
        return true
    }
    if indexPath.row > self.fetchedResultsController.sections![indexPath.section].objects!.count - 1 {
        return true
    }
    return false
}

override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath)
{
    if indexIsOutOfRange(destinationIndexPath) {
        return
    }

    isMovingItem = true


    if sourceIndexPath.section == destinationIndexPath.section {
        if var todos = self.fetchedResultsController.sections![sourceIndexPath.section].objects {
            let todo = todos[sourceIndexPath.row] as! FoodEntry
            todos.removeAtIndex(sourceIndexPath.row)
            todos.insert(todo, atIndex: destinationIndexPath.row)

            var idx = 1
            for todo in todos as! [FoodEntry] {
                todo.sortOrder = NSNumber(integer: idx++)
            }
            try!managedObjectContext.save()
        }
    } else {

        if var allObjectInSourceSection = fetchedResultsController.sections![sourceIndexPath.section].objects {
            let object = allObjectInSourceSection[sourceIndexPath.row] as! FoodEntry
            allObjectInSourceSection.removeAtIndex(sourceIndexPath.row)

            for (index,object) in (allObjectInSourceSection as! [FoodEntry]).enumerate() {
                object.sortOrder = NSNumber(integer: index)
            }


            if var allObjectInDestinationSection = fetchedResultsController.sections![destinationIndexPath.section].objects {

                allObjectInDestinationSection.insert(object, atIndex: destinationIndexPath.row)

                for (index,object) in (allObjectInDestinationSection as! [FoodEntry]).enumerate() {
                    object.sortOrder = NSNumber(integer: index)
                    object.section = NSNumber(integer: destinationIndexPath.section)
                }
            }
        }

    }


    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        tableView.reloadRowsAtIndexPaths(tableView.indexPathsForVisibleRows!, withRowAnimation: .Fade)
    })

    isMovingItem = false

    try!managedObjectContext.save()

    fetch()

}