【问题标题】:'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal'NSInvalidArgumentException',原因:'+entityForName: nil 不合法
【发布时间】:2018-01-16 16:21:39
【问题描述】:
 @IBAction func CreateButton(_ sender: AnyObject) {

    let appDelegate = (UIApplication.shared.delegate as! AppDelegate)

    let managedContext =
        appDelegate.persistentContainer.viewContext
    let entity =
        NSEntityDescription.entity(forEntityName: "EventData",
                                   in: managedContext)!


    let newEvent = NSManagedObject(entity: entity,
                                 insertInto: managedContext)


    newEvent.setValue( Venuetextfield.text!, forKey: "eventVenue")
    newEvent.setValue(Titletextfield.text!, forKey: "eventTitle")
    newEvent.setValue(Descriptiontextfield.text!, forKey: "eventDescription")
    newEvent.setValue(Datetime, forKey: "eventDateTime")
    // sending data to coredata.
    (UIApplication.shared.delegate as! AppDelegate).saveContext()

    let _ = navigationController?.popViewController(animated: true)
}

大家好,在 NSManagedObject 也在搜索实体名称的情况下,我怎样才能使 entityForName 不为零?

我还创建了一个包含所有实体属性的 NSMagedObject 类。

我需要将我的 Model.xcdatamodel id 文件链接到视图控制器类吗?

【问题讨论】:

    标签: swift core-data nsmanagedobject


    【解决方案1】:

    你应该这样做,

        let categoryMaster = NSEntityDescription.insertNewObject(forEntityName: "entity Name", into: managedContext) as! CategoryMaster //Here CategoryMaster is entity class which is the sub class of NSManageObject
    
        categoryMaster.categoryId = NSNumber.init(value: 1)
        categoryMaster.categoryIndent = NSNumber.init(value: 2)
        categoryMaster.categoryName = textFields.text
        categoryMaster.parentCategory = currentCategory.categoryId
        categoryMaster.categoryIndex = NSNumber.init(value: 0)
    
        guard (try? managedContext.save()) != nil else
        {
                fatalError("Something went wrong")
        }
    

    您可以查看整个教程here

    注意:这只是一个如何使用核心数据的示例,您可能会发现一些语法错误

    【讨论】:

    • 嘿 Hitesh 感谢您的回复,但您尚未声明“managedContext”。因此,当我按照您的建议对代码进行更改时,它会给我错误,例如“使用未解析的标识符 Managedobject”
    • 您好,我没有声明,因为您已经在问题代码中完成了声明
    • 是的,我已经猜到了那部分并对其进行了编辑,但现在它给出了错误“使用未声明的类型实体”
    • 我认为您的核心数据实体的实现存在一些问题,因此要验证所有内容,请参考我提供给您的教程链接,这样您就可以全面了解如何实现核心数据
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多