Reputation: 723
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.
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)")
}
}
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
saving in CoreData i think would solve the problem but any help or solution would be great.
Upvotes: 0
Views: 71
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