简体   繁体   中英

iOS - ManagedObjectContext is nil in swift CoreData

I'm facing this issue when I'm trying to save a simple string into CoreData.

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

The CoreData is set fine. And I use the following code to proceed.

func saveName(name: String) {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context: NSManagedObjectContext = appDelegate.persistentContainer.viewContext

        if context ==  nil {
            print("s")
        } else {
            print("d")
        }
        let entity = NSEntityDescription.insertNewObject(forEntityName: "CurrentUser", into: context)
        entity.setValue(name, forKey: "name")

        do {
            try context.save()
            print("saved")

        } catch {
            print("error")
        }    
    }

Calling:

saveName("Edwin")

This is the code from my project which was working fine until yesterday. I wonder what just happened. All of the sudden it starts showing that error I mentioned above.

Things I tried to find the problem:

  1. If I run my project on the simulator, the data is saved(works fine).
  2. Using the same code in another project works fine in both simulators and in the device.
  3. Tried deleting the previous build app and ran it again. (same result)

Things I found:

  1. ManagedObject context is nil when I run the code on the device but it is not nil when I run it on a simulator(thus it works fine on the simulator).
  2. ManagedObject Context is nil only when I run the code from my project(works fine in both simulator and device if I run the code in another project)

Help me with this strange problem.

I'm using Xcode 9.4.1 Swift: 4.1

Thanks in advance.

This is the most common problem faced in CoreData. In my case, I just recreated the data model and it worked. Thanks for the discussions in the comment section.

In my case the Core Data Model name was not matched with the project name Because I added it later in my project. Try it

I had the same problem, but thanks to Chris Chang of CodeWithChris in his IOS Databases lectures, I found a very interesting cause for this problem.

Be careful with this line of code:

let personListContext = PersistenceController.shared.container.viewContext

Make sure you include all 4 elements to the right side of the equal sign. And make sure to grab the correct context variable in your save.

let newPerson = PersonList(context: personListContext)
        do {
        try personListContext.save()
    } catch {
            let nsError = error as NSError
        fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM