' NSInvalidArgumentException',原因:' + entityForName:nil不合法

时间:2018-01-16 16:21:39

标签: swift core-data nsmanagedobject

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

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

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

1 个答案:

答案 0 :(得分:0)

你应该这样做,

    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

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