我将第一次使用CoreData。
但是,以下代码会导致错误。
我想尝试保存数据,但是它是“ nilError”。
你能告诉我如何解决吗?
func testCoreData(){
/// Base
let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
/// set
/// Error Log
/**
* Ok!!Save. id=fdsafdsfadf
* 2018-09-08 **:**:**.*****+0*** **[**:**]
* *** Terminating app due to uncaught exception
* 'NSInvalidArgumentException', reason: '+entityFo
* rName: nil is not a legal NSManagedObjectContext
* parameter searching for entity name 'Test''
*/
print("Ok!!Save. id=fdsafdsfadf")
let entity = NSEntityDescription.entity(forEntityName: "Test", in: context)
let newData = NSManagedObject(entity: entity!, insertInto: context)
newData.setValue("fdsafdsfadf", forKey: "id")
do{
try context.save()
}catch{
print(error)
}
}
答案 0 :(得分:2)
我在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: "Enter name of xcdatamodeld")...