Pablo R.
Pablo R.

Reputation: 723

Core Data update result values

I am trying to save in coreData an object list on moveRowAt. I am saving my data in a singleton and it is well ordered but when I update on Core Data it's never saved and the order is wrong.

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

for the first time it works well but never saved, i enter again and I move the new first item to the last position and this is what happens

its like i haven't done the first movement

saving in CoreData i think would solve the problem but any help or solution would be great.

Upvotes: 0

Views: 71

Answers (1)

Alexkater
Alexkater

Reputation: 76

I Don't know exactly what do you want to do, but by the way, you can order your array easily with.

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
}

Upvotes: 1

Related Questions