AppDelegate
具有以下成員只有
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
所以使用
let managedContext = (UIApplication.shared.delegate as! appDelegate).persistentContainer.viewContext
這將正常工作
您是否在創建新項目時選中了「使用核心數據」選項?這是必需的,因爲它在AppDelegate中添加了Core Data Stack的代碼。 – vadian
@vadian是的,我做到了。但是:我還檢查了基於文檔的應用程序,單元測試和UI測試。我注意到,當我檢查所有內容時,AppDelegate中沒有代碼,而只檢查CoreData ... – DaPhil
這很奇怪。提交一個錯誤。爲了解決您的問題,只檢查Core Data創建一個新項目,並將Core Data Stack複製並粘貼到基於文檔的項目中。 – vadian