iOS - 如何更新CoreDataModel实体?

时间:2017-04-21 10:07:55

标签: ios swift xcode8

我想从我的应用程序更新我的实体(在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
    }

在此模式下,我没有任何错误,但如果我尝试重新启动应用程序,则无法看到更新信息。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

您必须像这样保存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
    }
相关问题