Tanmay Baranwal Tanmay Baranwal - 2 years ago 104
Swift Question

Swift : Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Entity name must not be nil.'

I am trying to implement CoreData with my existing swift project. I followed this tutorial and implemented it with UITableView.

The data is getting added contentiously to the data model (from another view controller) when I am fetching data model record (in another view controller).


Navigating to the View Controller with UITableView, shows data from data model once. Tapping on the tableView or sliding it up or down causing the application to crash with error

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Entity name must not be nil.'

Function for saving record :

func saveData(date: String, usr : String, piid: String, healthD:String, temp:String, humd:String) {
let managedContext = DataController().managedObjectContext

let entity = NSEntityDescription.entityForName("Hygeine",

let health = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext: managedContext)

health.setValue(date, forKey: "date")
health.setValue(healthD, forKey: "health")
health.setValue(temp, forKey: "temp")
health.setValue(humd, forKey: "humd")
health.setValue(piid, forKey: "pi_id")
health.setValue(usr, forKey: "usr")
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")

ViewWillAppear for ViewController with UITableView :

override func viewWillAppear(animated: Bool) {

let managedContext = DataController().managedObjectContext

let fetchRequest = NSFetchRequest(entityName: "Hygeine")

do {
let results =
try managedContext.executeFetchRequest(fetchRequest)
healthData = results as! [NSManagedObject]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")

There are a lot of Objective-C solution to this problem but how to solve it in Swift 2. What I am doing wrong here ?

Answer Source

entityForName returns an optional that you are force unwrapping. That is most likely your error and easily caught in the debugger.

Is your entity name entered wrong? Check it against your model.

And as others have said, learn NSFetchedResultsController, while it won't solve this error, it is easier to work with when dealing with a UITableViewController.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download