首页 > 解决方案 > 无法将值保存到核心数据

问题描述

我正在尝试将数据存储到 Core-DataAppDelegate本身,然后从ViewController. 由于某种原因,它没有保存在 Core-Data 中。我已经尝试在互联网上搜索这个问题,但没有得到任何具体的解决方案。我已经粘贴了下面的代码 -

AppDelegate.swift

func saveContext () {
    let context = persistentContainer.viewContext
    print(context)
    let entity = NSEntityDescription.entity(forEntityName: "Msg", in: context)
    print(entity)
    let new = NSManagedObject(entity: entity!, insertInto: context)
    print(new)
    print(getData.alert_message)
    new.setValue(getData.alert_message, forKey: "title")
    do {
        try context.save()
        print("save")
        print(new.value(forKey: "title"))
    } catch {
        let nserror = error as NSError
        fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
    }  
}

控制台输出

在此处输入图像描述

标签: iosswiftcore-dataappdelegate

解决方案


 Hear I have Set My Own Solution, Hope This help You


let contex = ((UIApplication.shared.delegate) as! AppDelegate).persistentContainer.viewContext

func SaveData()
 {
 let entity = NSEntityDescription.insertNewObject(forEntityName: "Employee", into: contex);
        entity.setValue(txtname.text, forKey: "empname") // txtname.text is My TexField name 
        entity.setValue(txtadd.text, forKey: "empadd");
        do
        {
            try contex.save();
        }
        catch
        {

        }
 }

推荐阅读