核心数据更新结果值

时间:2017-09-19 09:10:05

标签: ios swift swift3

我想在coreData中保存moveRowAt上的一个对象列表。我将数据保存在一个单例中并且排序很好但是当我更新Core Data时它从未保存并且顺序错误。

This is my list, I moved first item to 4 position Singleton ordered

func changeKrakenPosition(source: Int, destiny: Int){

    let context = appDelegate.persistentContainer.viewContext
    do {
        var results = try context.fetch(fetchRequest)
        var source = source
        var destiny = destiny
        var destinyItem = results[destiny]
        var sourceItem = results[source]

        if source < destiny {
            var dif = destiny - source
            for i in 0...dif {
                if i != dif {
                    var krakenCoreDataToMove = results[source+1]
                    results[source] = krakenCoreDataToMove
                    source += 1
                } else {
                    results[source] = destinyItem
                }
            }
            results[destiny] = sourceItem
        } else if destiny < source {
            var dif = source - destiny
            for i in 0...dif {
                if i !=  dif{
                    var krakenCoreDataToMove = results[source-1]
                    results[source] = krakenCoreDataToMove
                    source -= 1
                } else {
                   results[source] = destinyItem
                }
            }
            results[destiny] = sourceItem
        } else {
            //Moved to same position
        }

        var resultKra = results as! [Kraken]
        for res in resultKra {
            print("name:  \(res.name) age \(res.age)")
        }

        do {
            try context.save()
        }catch{
            //Handle Error
        }

    } catch {
        print("Error with request: \(error)")
    }

}

first time ordering Core Data

第一次运作良好但从未保存过,我再次进入,我将新的第一个项目移动到最后一个位置,这就是发生的事情

its like i haven't done the first movement

保存在CoreData中我认为可以解决问题,但任何帮助或解决方案都会很棒。

1 个答案:

答案 0 :(得分:1)

我不确切地知道你想做什么,但顺便说一下,你可以轻松地订购你的阵列。

struct CustomObject{
    let i: Int
    let j: String
}

var array: [CustomObject] = [
    CustomObject(i: 1, j: "1"),
    CustomObject(i: 0, j: "0"),
    CustomObject(i: 3, j: "3"),
                            ]

let newArray = array.sorted { (first, second) -> Bool in
    first.i < second.i
}