带部分的UITableView CoreData订单

时间:2016-06-06 14:36:17

标签: swift uitableview cocoa-touch core-data swift2

我正在寻找一些类似的场景,但我找不到包含我需要的所有功能的任何内容。环顾四周我写了方法moveRowAtIndexPath的实现,如下所示,但是我修改了对coredata对象的引用有一些问题,所以当我点击完成时,没有任何内容保存在coredata上。

override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
    userDrivenDataModelChange = true;

    if (sourceIndexPath == destinationIndexPath) {
        return
    }

    let rooms = fetchedResultsController.sections!

    let sourceRoom = rooms[sourceIndexPath.section]
    let destinationRoom = rooms[destinationIndexPath.section]

    var sourceLights = sourceRoom.objects as! [Light]
    var destinationLights = destinationRoom.objects as! [Light]
    let light = sourceLights[sourceIndexPath.row]

    sourceLights.removeAtIndex(sourceIndexPath.row)
    destinationLights.insert(light, atIndex: destinationIndexPath.row)

    (destinationLights as NSArray).enumerateObjectsUsingBlock({ object, index, stop in
        let light = object as! Light
        light.position = index
    })

    tableView.reloadData()

    Utils.saveContext(getAppDelegate().context)

    userDrivenDataModelChange = false;
}

2 个答案:

答案 0 :(得分:1)

缺少的部分是将新房间设置为我要移动的项目。类似的东西:

item.relationRoom = <destination room object>

当您在同一房间内移动灯光时,还需要进行一些调整。

答案 1 :(得分:0)

您的代码不必要地复杂。您可以将灯光对象放在一行中。

let light = fetchedResultsController.objectAtIndexPath(sourceIndexPath) as! Light

更新灯光的position属性实际上是IMO属于Room类的内容。您应该编写便利方法,在添加和移除(并且可能移动)轻型对象时重新编号所有相关的灯光实例。

请注意,如果将灯光移动到其他房间(即源索引路径和目标索引路径具有不同的部分),则可能必须在两个不同的房间调用此方法。

另外,需要重新加载整个表视图。如果你还不是最重要的话,这是完全冗余和糟糕的用户体验。

请注意,在您的代码中,您只是从获取的结果控制器修改sections数组。我要保存到核心数据,你必须修改关系(大概是Room)并保存。