【发布时间】:2017-06-07 16:52:01
【问题描述】:
我正在尝试将实体添加到集合中,但在应用程序关闭后它不会持续存在。我的关系是这样的:
我像这样创建一个新任务:
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)")
}
组正确填充,我拥有我创建的所有组。但不存在任何关系。这什么也不打印:
let set = groups[0].mutableSetValue(forKey: "tasks")
for tasks in set{
print(tasks)
}
如果我不打开和关闭应用程序,此代码会打印任务。出于某种原因,应用程序关闭时数据不会保留。有任何想法吗?谢谢
【问题讨论】:
-
您是否在将任务添加到组后保存上下文?我在上面的示例中没有看到它。必须这样做。
-
不相关,但不要保护
AppDelegate。强行拆开。如果课程丢失,您的应用甚至都不会启动。