【问题标题】:Get entity name from Core Data record stored in Cloudkit从存储在 Cloudkit 中的核心数据记录中获取实体名称
【发布时间】:2020-11-13 21:37:38
【问题描述】:

我有一个包含 3 个实体的核心数据模型:员工、运动员和治疗师。 Employee 是一个抽象实体,因此我在 Xcode 中将 Employee 标记为另外两个实体的父级。每个实体的 Codegen 设置为 Class Definition。现在我正在写逻辑......

  1. 获取所有员工记录[工作]
  2. 循环遍历每条记录[工作]
  3. 获取记录的实体名称
  4. 根据实体名称显示不同的 SwiftUI 视图

我被困在 3 上。我通读了 Apple's documentation 并看到 Cloudkit 为每个名为 CD_entityName 的记录添加了一个属性,其中包含定义的实体名称的适当字符串(“运动员”或“治疗师”)在核心数据中......但我仍然很困惑。如何获取记录的实体名称并使用它来通知我的视图逻辑?

由于CD_entityName 存在于 CloudKit 的数据模型表示中,我是否还需要在我的核心数据模型中为 CD_entityName 创建一个属性?

下面是我的ContentView.swift 文件。当我尝试构建应用程序时,我收到一条错误消息,提示 Employee has no member 'CD_entityName'。

struct ContentView: View {

    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Employee.date_added, ascending: false)], animation: .default)
    private var allEmployees: FetchedResults<Employee>
    
    // * Body * //
    var body: some View {
            
            List {
                
                ForEach(allEmployees) { employee in

                    switch employee.CD_entityName {
                        case "Athlete":
                            AthleteRowView(athlete: employee as! Athlete)
                        case "Sound":
                            TherapistRowView(therapist: employee as! Therapist)
                        default:
                            print("Error: Unknown entityName for record")
                    }
                }
            }
        
    } // end Body
    
} // end ContentView

【问题讨论】:

    标签: swift core-data swiftui cloudkit ios14


    【解决方案1】:

    试试下面的

    switch employee.entity.name {
        case "Athlete":
            AthleteRowView(athlete: employee as! Athlete)
        case "Sound":
            TherapistRowView(therapist: employee as! Therapist)
        default:
            EmptyView()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-11
      • 2017-09-08
      • 1970-01-01
      • 2018-07-27
      相关资源
      最近更新 更多