gpt4 book ai didi

swift : '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name ' 测试''

转载 作者:行者123 更新时间:2023-11-28 10:38:11 25 4
gpt4 key购买 nike

我会第一次使用CoreData。
但是,以下代码会导致错误。
我想尝试保存数据,但它是“nilError”。
能告诉我怎么解决吗?

func testCoreData(){
/// Base
let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext

/// set

/// Error Log
/**
* Ok!!Save. id=fdsafdsfadf
* 2018-09-08 **:**:**.*****+0*** **[**:**]
* *** Terminating app due to uncaught exception
* 'NSInvalidArgumentException', reason: '+entityFo
* rName: nil is not a legal NSManagedObjectContext
* parameter searching for entity name 'Test''
*/

print("Ok!!Save. id=fdsafdsfadf")
let entity = NSEntityDescription.entity(forEntityName: "Test", in: context)
let newData = NSManagedObject(entity: entity!, insertInto: context)
newData.setValue("fdsafdsfadf", forKey: "id")
do{
try context.save()
}catch{
print(error)
}

}

The Image of .xcdatamodeld

最佳答案

我在 AppDelegate 代码中犯了一个错误。

// MARK: - Core Data stack

lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Enter name of xcdatamodeld")...

关于 swift : '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name ' 测试'',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52235616/

25 4 0