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:
Things I found:
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.