@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不为零?

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

我是否需要链接Model.xcdatamodel id文件以查看控制器类?

最佳答案

你应该这样

    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

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

关于swift - 'NSInvalidArgumentException',原因:'+ entityForName:nil不合法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48285673/

10-10 21:08