[英]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. 我正在尝试使用现有的Swift项目来实现CoreData。 I followed this tutorial and implemented it with UITableView. 我遵循了本教程 ,并使用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). 当我获取数据模型记录(在另一个视图控制器中)时,数据争执地添加到了数据模型(从另一个视图控制器中)。
Problem 问题
Navigating to the View Controller with UITableView, shows data from data model once. 使用UITableView导航到View Controller,一次显示数据模型中的数据。 Tapping on the tableView or sliding it up or down causing the application to crash with error 轻击tableView或向上或向下滑动会导致应用程序崩溃并出现错误
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Entity name must not be nil.' 由于未捕获的异常“ NSInvalidArgumentException”而终止应用程序,原因:“实体名称不能为零。”
Function for saving record : 保存记录功能:
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)")
}
}
ViewWillAppear for ViewController with UITableView : 用于带有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)")
}
}
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 ? 这个问题有很多Objective-C解决方案,但是如何在Swift 2中解决。
entityForName
returns an optional that you are force unwrapping. entityForName
返回一个可选的,您可以强制展开。 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
. 正如其他人所说,学习NSFetchedResultsController
虽然不会解决此错误,但在处理UITableViewController
时更容易使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.