【问题标题】:UITableView CoreData order with sections带有部分的 UITableView CoreData 顺序
【发布时间】:2016-06-06 14:36:17
【问题描述】:

我正在四处寻找一些类似的场景,但我找不到任何包含我需要的所有功能的东西。环顾四周,我编写了 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;
}

【问题讨论】:

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


    【解决方案1】:

    缺少的部分是将新房间设置为我要移动的项目。比如:

    item.relationRoom = <destination room object>
    

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

    【讨论】:

      【解决方案2】:

      您的代码过于复杂。一行就可以得到灯光对象。

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

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

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

      另外,您确实不需要需要重新加载整个表格视图。如果您还没有名列前茅,那将是完全多余且糟糕的用户体验。

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

      【讨论】:

      • 关于获取灯光对象的好技巧。但是关于排序,这已经通过 enumerateObjectsUsingBlock 方法完成了,但是更改并没有以某种方式持续到 CoreData,可能是该对象与 CoreData 分离,如果是这样 - 如何解决它?
      • 这段代码不属于视图控制器。你应该听从我的建议。
      • 好的,你有例子吗?我仍然不明白如何让我的代码工作。
      • 您需要修改Light 对象所属的Room 对象,而不是您从fetchedResultsController 中复制的部分。
      猜你喜欢
      • 2015-12-31
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-09
      • 2014-01-21
      相关资源
      最近更新 更多