2016-09-27 23 views
0

我想更新我的核心數據實體和我的代碼是:如何更新核心數據中的對象?

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") 
} 

元素被更新的核心數據,但它也增加了一個新行我tableView一個空數據。

+0

爲什麼在保存數據後調用'self.viewDidLoad()'? – CodeChanger

+0

重新計算購物車 –

+0

你只想更新'數量'值,對不對? –

回答

0

如果要更新當前對象ffquantity,請嘗試使用這些行。

 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") 
     } 

你爲什麼叫self.viewDidLoad()

在您的下一個代碼中,您正在創建一個新項目,而不僅僅是更新當前項目。

+0

要再次計算購物車,將價格的變化量乘以價格 –

+0

確定它正在工作,但我需要在更改時更新視圖 –

+0

好的完美! ;)但不建議直接調用'viewDidLoad:'可能你應該重構一點點 – thedjnivek