gpt4 book ai didi

ios - 无法将值保存到核心数据

转载 作者:行者123 更新时间:2023-11-28 14:24:47 24 4
gpt4 key购买 nike

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

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)")
}
}

控制台输出

enter image description here

最佳答案

您可以通过NSFetchRequest从实体中获取记录

试试下面的方法,你只需要传递实体的名称作为函数的参数。

func getAllRecordFromTableWhere(_ tableName: String) -> [NSManagedObject]? {
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: tableName)
do {
return try managedContext.fetch(fetchRequest)
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
return nil
}

然后像这样调用函数

if let arrayOfData = DBHelper.getAllRecordFromTableWhere("Msg") {
print(arrayOfData)
}

关于ios - 无法将值保存到核心数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51701235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com