fdsafdsa fdsafdsf
fdsafdsa fdsafdsf

Reputation: 131

Swift: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Test''

I will use CoreData for the first time.
However, the following code causes an error.
I would like to try saving the data, but it is "nilError".
Could you tell me how to solve it?

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)
    }

}

The Image of .xcdatamodeld

Upvotes: 2

Views: 3753

Answers (2)

Hitesh Takhtani
Hitesh Takhtani

Reputation: 11

Also Make Sure to Select target membership, after creating data model in XCDATAMODEL file

enter image description here

Upvotes: 0

fdsafdsa fdsafdsf
fdsafdsa fdsafdsf

Reputation: 131

I made a mistake in AppDelegate code.

// 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")...

Upvotes: 10

Related Questions