ios - 无法将值保存到核心数据
问题描述
我正在尝试将数据存储到 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)")
}
}
控制台输出
解决方案
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
{
}
}
推荐阅读
- python - 如何在 irq() 中运行 irq() ?或在第二个 irq 上禁用一个 irq?
- spring - Changing Rest controller method signature
- emacs - How to select or highlight text without mouse
- react-native - 如何撤消 react-native-upgrade?
- php - Having difficulties displaying all content on my wishlist table
- javascript - Promise.all() 函数中的 JS 'await 仅在异步函数中有效'
- assembly - Irvine ch10. Three-Operand Instructions using Macro in MASM
- javascript - Angular: Load dynamic component
- css - Cropping the top 10% of an image using CSS?
- apollo-server - Apollo Federation 网关和另一个服务器实现