假设我有一个核心数据对象数组。
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,现在数组中的对象具有以下indexValues
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/