ben fo ben fo - 2 months ago 13
iOS Question

How to update objects in core data?

I want to update my core data entity and I have this code now:

let ff: Cart!
let indexPath = self.tableView?.indexPathForSelectedRow
ff = self.cart[indexPath!.row]

let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext

let entity = NSEntityDescription.entityForName("Cart", inManagedObjectContext: context)
let cartt = Cart(entity: entity!, insertIntoManagedObjectContext: context)
cartt.name = ff.name
cartt.price = Double(ff.price!)
cartt.rest_id = ff.rest_id
cartt.longg = ff.longg
cartt.latt = ff.latt
cartt.item_id = ff.item_id
cartt.restName = ff.restName
cartt.cookTime = ff.cookTime

ff.setValue(Int(txt.text!), forKey: "quantity")

do{
try context.save()
self.viewDidLoad()
print(cartt.longg)
print(cartt.delivery)
print("saved")

}catch{
print("could not save")
}


The element is updating in the core data, but it is also adding a new row to my
tableView
with an empty data.

Answer

If you want to update quantity of the current object ff try with these lines.

        let ff: Cart!
        let indexPath = self.tableView?.indexPathForSelectedRow
        ff = self.cart[indexPath!.row]
        let app = UIApplication.sharedApplication().delegate as! AppDelegate
        let context = app.managedObjectContext
        ff.setValue(Int(txt.text!), forKey: "quantity")
        do{
            try context.save()
            self.viewDidLoad() // why you call this line here ?
            print(cartt.longg)
            print(cartt.delivery)
            print("saved")
        }catch{
            print("could not save")
        }

Why did you call self.viewDidLoad()?

On your next code, you was creating a new item rather than just updating the current one.

Comments