代码之家  ›  专栏  ›  技术社区  ›  Glenncito

我很难根据与谓词的关系从核心数据中提取实体

  •  0
  • Glenncito  · 技术社区  · 9 年前

    快速背景 :我有一个ExamEntity,它通过一个关系链接到考试中涉及的部分(SectionEntity),它通过关系链接到每个部分下的子部分(SubsectionEntity)。

    我想做的是 获取所选考试将涵盖的部分和相关子部分,并将其存储在字典中,该字典可以为每个关键字保存多个字符串值。

    我的代码是这样开始的:

    var sectionsDictionary = [String:[String]]()
    
        //---Fetch Section Entity
        let sectionPredicate = NSPredicate(format: "(exam = %@)", selectedExam)
    
        let sectionsFetchRequest:NSFetchRequest = SectionEntity.MR_requestAllWithPredicate(sectionPredicate)
    
        let fetchedSections:NSArray = SectionEntity.MR_executeFetchRequest(sectionsFetchRequest)
    

    这里一切都很好。但随后我尝试获取与所选部分相关的子部分,结果出现了问题。

    以下代码:

      for section in fetchedSections {
            let sectionName = section.valueForKey("name") as! String
    
            // //error occurs on the line below
            let subsectionPredicate = NSPredicate(format: "(section = %@)", section as! SectionEntity)
    
            let subsectionsFetchRequest:NSFetchRequest = SubsectionEntity.MR_requestAllWithPredicate(subsectionPredicate)
    
    
            let fetchedSubsections:NSArray = SubsectionEntity.MR_executeFetchRequest(subsectionsFetchRequest)
    

    我得到的错误是:

    Could not cast value of type 'NSManagedObject_SectionEntity_' (0x7fb363e18580) to 'MyApp.SectionEntity' (0x10c9213e0). 
    

    接下来的几行将遍历获取的结果,将它们的名称作为值添加到字典中,并将节名作为关键字。

              for subsection in fetchedSubsections{
                let subsectionName = subsection.valueForKey("name") as! String
                sectionsDictionary[sectionName] = [subsectionName]
            }
    
        }
    

    提前感谢。

    2 回复  |  直到 9 年前
        1
  •  1
  •   dGambit    9 年前

    您没有为记录定义类的类型

    转到 项目.xcdatamodeld 文件,然后选择 SectionEntity

    检查“类”字段是否如下

    enter image description here

    如果在Class字段“SectionEntity”中写入并按Enter键,则应该如下所示

    enter image description here

    然后再试一次

        2
  •  0
  •   Community CDub    7 年前

    您需要确保枚举的集合元素的类型正确。

    据推测,Magical Record将返回 NSArray 属于 NSManagedObject 项目。你需要确保斯威夫特知道什么类型 section

    for object in fetchedSections {
       let section = object as! SectionEntity
       // ...
    }    
    

    另外,请参见我的 answer 关于不成功的演员 被管理对象 子类。