ios - 如何更新核心数据中的对象?

标签 ios swift uitableview core-data

我想更新我的核心数据实体,我的代码是:

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 添加了新行。

最佳答案

如果您想更新当前对象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()

在下一个代码中,您将创建一个新项目,而不仅仅是更新当前项目。

关于ios - 如何更新核心数据中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39720108/

相关文章:

ios - 如何在 Swift 中编辑 textField 时刷新键盘/returnKey?

swift - 在 4 个单元格中只添加了 1 个 SubView

ios - 在异步方法中准备好数据后如何重新加载 TableView 的数据

ios - UITextField.Text 从其他 View 返回 null

ios - 需要帮助将新的存储属性添加到 UITableView

ios - tableView的顶部有一些空白区域

Objective-C:NSNumber 对象的平滑 NSArray

ios - 在 .xib 中使用自定义 UIView 作为 IBOutlet

ios - 如何对静态单元格进行编程以从 Storyboard中获取高度,同时对其他单元格进行编程以从代码中获取高度

swift - 共享数据源时如何识别哪个 UIPickerView 收到事件