Ios 核心数据关系不持久
我试图向集合中添加一个实体,但它在应用程序关闭后不会持久化。我的关系是这样的:Ios 核心数据关系不持久,ios,arrays,core-data,Ios,Arrays,Core Data,我试图向集合中添加一个实体,但它在应用程序关闭后不会持久化。我的关系是这样的: guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } // 1 let managedContext = appDelegate.persistentContainer.viewContext // 2
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)
我创建了一个新任务,如下所示:
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)
我将任务添加到组实体,如下所示:
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)
其中groups是一个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
。强行打开它。如果类丢失,你的应用程序甚至不会启动。