0

Quick background: I have en ExamEntity, which is linked via a relationship to sections covered in the exam (SectionEntity), which is linked via a relationship to the subsections under each section (SubsectionEntity).

What I'm try to do is fetch the sections and related subsections which will be covered be a selected Exam, and store them in a dictionary which can hold multiple string values per key.

My code starts like this:

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)

All good here. But then I try and fetch the subsections related to the selected sections and things go wrong.

following Code:

  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)

The error I get is:

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

The next few lines are supposed to iterate through the fetched results, adding their names as values to the dictionary with section names as keys.

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

    }

thanks in advance.

Glenncito
  • 902
  • 1
  • 10
  • 23
  • Did you set the class of your `SectionEntitiy` in the core data model editor to `SectionEntity`? Or is it still the default, `NSManagedObject`? – Cornelius Aug 12 '15 at 21:17

2 Answers2

1

You're not defining the type of the class for your record

Go to the Project.xcdatamodeld file, and select your SectionEntity

Check if the field Class is like this

enter image description here

If it is then write in the Class field "SectionEntity" and press Enter, it should be like this

enter image description here

Then try again

dGambit
  • 531
  • 3
  • 11
0

You need to make sure that the elements of the collection you enumerate are of the correct type.

Presumably, Magical Record will return an NSArray of NSManagedObject items. You need to make sure Swift knows what type section is.

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

Also, see my answer about the unsuccessful casts to NSManagedObject subclasses.

Community
  • 1
  • 1
Mundi
  • 79,884
  • 17
  • 117
  • 140