0
我正试图添加一个实体到一个集合中,但在应用程序关闭后它不会持久化。我的关系是这样的:核心数据关系不坚持
我创建了一个新的任务是这样的:
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
// 1
let managedContext =
appDelegate.persistentContainer.viewContext
// 2
let entity =
NSEntityDescription.entity(forEntityName: "Task",
in: managedContext)!
let task = NSManagedObject(entity: entity,
insertInto: managedContext)
// 3
task.setValue(cell.taskTextField.text, forKeyPath: "name")
// 4
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
我的任务添加到组实体是这样的:
groups[0].mutableSetValue(forKey: "tasks").add(task)
哪里组是一个NSManagedObject数组,其值在viewDidLoad:
中加载,如下所示:
//1
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext =
appDelegate.persistentContainer.viewContext
//2
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "Group")
//3
do {
groups = try managedContext.fetch(fetchRequest)
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
组填充正确,我有我创建的所有组。但是不存在任何关系。这不打印:
此代码打印提供的任务,我不打开和关闭应用程序。出于某种原因,应用程序关闭时数据不会持续存在。有任何想法吗?谢谢
您是否在将任务添加到组之后保存上下文?我在上面的例子中没有看到它。这必须完成。 –
不相关,但不要保护'AppDelegate'。强制拆包。如果课程缺失,您的应用程序甚至不会启动。 – vadian