Swift: '+entityForName: nil 不是一个合法的 NSManagedObjectContext 参数搜索实体名称 'Test''

fds*_*dsf 2 core-data swift

我将第一次使用 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)
    }

}
Run Code Online (Sandbox Code Playgroud)

.xcdatamodeld 的图像

fds*_*dsf 8

我在 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")...
Run Code Online (Sandbox Code Playgroud)