我有这个核心数据模型:(DashboardEntity是Visit and Log的父级)
ios - 将子实体附加到Core Data iOS Swift中的实体-LMLPHP

现在,我将DashboardEntity子类化为继承自NSManagedObject的类。我也将VisitEntityLogEntity分为两个子类,都继承自DashboardEntity

我想将条目添加到DashboardEntity,但是我希望该条目是VisitEntity,这应该是可能的,因为它是从DashboardEntity继承的,如下所示:

                // Fething dashboard entity
                var dashboard = [DashboardEntity]()
                let fetchRequest = NSFetchRequest(entityName: "DashboardEntity")

                // Returning results as an array of DashboardEntities
                do {
                    let results = try managedContext.executeFetchRequest(fetchRequest)
                    dashboard = results as! [DashboardEntity]
                } catch let error as NSError {
                    print("Could not fetch \(error), \(error.userInfo)")
                }


                // Point to DashboardEntity from my database
                let entity =  NSEntityDescription.entityForName("DashboardEntity", inManagedObjectContext:managedContext)

                // Here I create an object of type VisitEntity, that takes an extra parameter that converts json to properties
                let person: VisitEntity = VisitEntity (entity: entity!, insertIntoManagedObjectContext: managedContext, jsonData: index)

                // I append this new object to
                do {
                    try managedContext.save()
                    dashboard.append(person)
                } catch let error as NSError  {
                    print("Could not save \(error), \(error.userInfo)")
                }


但是发生错误:


  “无法识别的选择器已发送到实例”,setManager是选择器
  (来自VisitEntity,因为它在DashboardEntity上不可用)。


如果我有一个X对象的普通数组,并且想添加一个继承自它的对象,那么我可以在Swift中做到这一点,为什么它不能与Core Data NSManagedObjects一起使用?

如果我添加DashboardEntity对象,一切正常。

这样做的原因是,我有一个UITableViewController可以同时包含“访问”和“日志”,这取决于单元格表具有某些选项还是其他选项。

谢谢大家!

最佳答案

在我看来,这里的两行:

 // Point to DashboardEntity from my database
let entity =  NSEntityDescription.entityForName("DashboardEntity", inManagedObjectContext:managedContext)

// Here I create an object of type VisitEntity, that takes an extra parameter that converts json to properties
let person: VisitEntity = VisitEntity (entity: entity!, insertIntoManagedObjectContext: managedContext, jsonData: index)


创建一个VisitEntity人实例,为其提供一个实体参数,其中NSEntityDescription为“ DashboardEntity”而不是“ VisitEntity”

因此,当尝试设置manager属性时,应用程序说DashboardEntity没有成员“ manager”。

也许尝试将实体描述设置为VisitEntity:

// Point to DashboardEntity from my database
let entity =  NSEntityDescription.entityForName("VisitEntity", inManagedObjectContext:managedContext)

// Here I create an object of type VisitEntity, that takes an extra parameter that converts json to properties
let person: VisitEntity = VisitEntity (entity: entity!, insertIntoManagedObjectContext: managedContext, jsonData: index)

10-08 12:56