So I've been learning and working with CoreData
, and I've been very frustrated by the following problem. When I start my App, I want to fetch my CoreData
as the custom NSManagedObject
subclass that I've created. But the forced down casting never works. I've followed the Apple guide.
My data is the following. Below is the custom NSManagedObject
subclass:
import UIKit
import CoreData
@objc(StudentUniversityData)
class UniversityData: NSManagedObject {
@NSManaged var universityName:String
@NSManaged var chineseName:String
@NSManaged var bottomReadingPercentile:NSNumber
@NSManaged var bottomMathPercentile:NSNumber
@NSManaged var topReadingPercentile:NSNumber
@NSManaged var topMathPercentile:NSNumber
}
Here is the code I've created:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let studentUniversityFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "StudentUniversityData")
studentUniversityFetchRequest.returnsObjectsAsFaults = false
do {
let studentUniversityResults = try managedContext.fetch(studentUniversityFetchRequest)
savedUniversities = studentUniversityResults as! [UniversityData] // the problem is HERE; this part never works
} catch let error as NSError {
print ("Could not fetch \(error), \(error.userInfo)")
}
}
Here is one picture of my CoreData
entity.
Here is another picture of my CoreData
entity
No matter what I try to do, the savedUniversities
property is always nil.
Also, I read that having multiple targets will screw up the code. So I made sure that all my classes only have one target (I took out the tests and UItests target membership). Still doesn't work.
Sorry if this isn't very clear, as I'm very tired and have worked on this problem for hours (without any progress). I've read many questions on Stack Overflow, like:
Unable to find specific subclass of NSManagedObject
CoreData: warning: Unable to load class named
Core Data: Could not cast value of type 'MyType_MyType_2' to MyType
But I'm still stuck.
So I was able to solve my problem after another half-day.
What I did was rename my Core Data entity to "UniversityData". That made it match the NSManagedObject subclass "UniversityData."
Everything works after the names match.
It seems that a lot of Core Data only works if the names match exactly with everything in your subclasses.