iOS - 如何更新 CoreDataModel 实体?

iOS - How can I update CoreDataModel Entities?

我想从我的应用更新我的实体(在 Swift 3 和 Xcode 8 中)。

所以我使用了核心数据模型。

这是我的代码 CoreDataController.swift:

// Updates a person
    func update(updateLuci: LuciKit){
        if let luci = getById(id: updateLuci.objectID){
            luci.descrizione = updateLuci.descrizione
            luci.pin_arduino = updateLuci.pin_arduino
        }
    }

    // Gets a person by id
    func getById(id: NSManagedObjectID) -> LuciKit? {
        return context.object(with: id) as? LuciKit
    }

在这种模式下我没有任何错误,但是如果我尝试重新启动我的应用程序我看不到更新信息。

试试这个,我想你忘了保存上下文

func update(updateLuci: LuciKit){
        if let luci = getById(id: updateLuci.objectID){
            luci.descrizione = updateLuci.descrizione
            luci.pin_arduino = updateLuci.pin_arduino
            context.save()
        }
    }

您必须像这样保存 context

func update(updateLuci: LuciKit){
        if let luci = getById(id: updateLuci.objectID){
            luci.descrizione = updateLuci.descrizione
            luci.pin_arduino = updateLuci.pin_arduino

            //let delegate = UIApplication.shared.delegate as! AppDelegate
            //let context = delegate.managedObjectContext

            do {
                try context.save()
            } catch let err {
                print(err)
            }
        }
    }

    // Gets a person by id
    func getById(id: NSManagedObjectID) -> LuciKit? {
        return context.object(with: id) as? LuciKit
    }