我想更新我的核心数据实体,我的代码是:
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
添加了新行。
最佳答案
如果您想更新当前对象ff
的quantity
,请尝试使用这些行。
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()
?
在下一个代码中,您将创建一个新项目,而不仅仅是更新当前项目。
关于ios - 如何更新核心数据中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39720108/