ios - swift : Terminating app due to uncaught exception 'NSInvalidArgumentException' , 原因: 'Entity name must not be nil.'

标签 ios iphone swift uitableview core-data

我正在尝试用我现有的 swift 项目实现 CoreData。我关注了this tutorial并使用 UITableView 实现它。

当我获取数据模型记录(在另一个 View Controller 中)时,数据被有争议地添加到数据模型(从另一个 View Controller )。

问题

使用 UITableView 导航到 View Controller ,显示一次来自数据模型的数据。点击 tableView 或向上或向下滑动导致应用程序崩溃并报错

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

记录保存功能:

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

        //2
        let entity =  NSEntityDescription.entityForName("Hygeine",
            inManagedObjectContext:managedContext)

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

        //3
        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")
        //4
        do {
            try managedContext.save()
            //5
            healthData.append(health)
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
        }
    }

带有 UITableView 的 ViewController 的 ViewWillAppear:

override func viewWillAppear(animated: Bool) {

        let managedContext = DataController().managedObjectContext

        //2
        let fetchRequest = NSFetchRequest(entityName: "Hygeine")

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

有很多针对此问题的 Objective-C 解决方案,但如何在 Swift 2 中解决它。我在这里做错了什么?

最佳答案

entityForName 返回一个您要强制解包的可选值。这很可能是您的错误,很容易被调试器捕获。

您的实体名称输入有误吗?根据您的模型检查它。

正如其他人所说,学习 NSFetchedResultsController,虽然它不会解决这个错误,但在处理 UITableViewController 时更容易处理。

关于ios - swift : Terminating app due to uncaught exception 'NSInvalidArgumentException' , 原因: 'Entity name must not be nil.',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36776541/

相关文章:

iphone - Game Center 分数停留在特定分数

ios - 更改设备方向时重绘自定义 uiview

iphone - 填充 UIBezierPath

ios - 使用 NSFetchedResultsController 的 CoreData 性能。 UITableView 在数据导入期间卡住

Swift 包管理器 - 框架分发

ios - UINavigationController 不推送 View Controller

html - 如何在一段 NSAttributedString 周围制作一个框

iphone - 在 iPhone 底部添加 StatusBar

ios - 如何从ios中的文档目录复制不同类型的文件

ios - 数组数减去数组数