假设我有一个 Core Data 对象数组。
let array = [Object1, Object2, Object3, Object4, Object5, Object6, Object7]
每个对象都有一个名为 indexValue : Int64 的属性
首先,这些对象具有以下 indexValue 属性值:
Object1 has indexValue = 1
Object2 has indexValue = 2
Object3 has indexValue = 3
Object4 has indexValue = 4
Object5 has indexValue = 5
Object6 has indexValue = 6
Object7 has indexValue = 7
现在假设我删除了 Object3 和 Object6,现在数组中的对象具有以下索引值
Object1 has indexValue = 1
Object2 has indexValue = 2
Object4 has indexValue = 4
Object5 has indexValue = 5
Object7 has indexValue = 7
删除后,我想按以下方式重新排序该数组: 我想将此数组的 indexValue 属性更改为以下状态:
Object1 has indexValue = 1
Object2 has indexValue = 2
Object4 has indexValue = 3
Object5 has indexValue = 4
Object7 has indexValue = 5
主要的困难是在给出新的indexValue值的同时保持旧的顺序。我正在寻找一种算法来在 Swift 3 中完成此任务。
最佳答案
简单的解决方案,使用此函数并传递缺少索引的有序数组。
您必须将 MyObject
替换为包含 indexValue
属性的实际自定义类型,并添加代码以保存托管对象上下文。
func reindex(items : [MyObject])
{
for (index, item) in items.enumerated() {
item.indexValue = Int64(index + 1)
}
// save the context
}
关于arrays - 如何在 Swift 3 中重新排序核心数据对象数组并重新排序其 Int 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45458713/