问题
I am using Core Data in Swift and am having trouble storing the array returned from a fetch request. I have two entities in my data model: Task and Homework. Homework's parent entity is Task. I auto generated the classes for the two entities:
Task.swift
import Foundation
import CoreData
class Task: NSManagedObject {
@NSManaged var name: String
@NSManaged var due: NSDate
@NSManaged var subject: Subject
}
Homework.swift
import Foundation
import CoreData
class Homework: Task {
}
In my view controller, in view did load, I have the following code.
var error: NSError? = nil
let fetchRequest = NSFetchRequest()
let entity = NSEntityDescription.entityForName("Task", inManagedObjectContext: managedObjectContext)
fetchRequest.entity = entity
tasks = managedObjectContext.executeFetchRequest(fetchRequest, error: &error) as [Task]
Earlier in the view controller, I initialized tasks:
var tasks : [Task] = []
However, when I run the the application, I get the following runtime error at the line where I assign the array to tasks: fatal error: array cannot be downcast to array of derived
If I replace the assignment line with var temp = managedObjectContext.executeFetchRequest(fetchRequest, error: &error) as [NSManagedObject], the error does not occur, but I need to save it as an array of Tasks in order to be able to use the custom classes that I generated. What am I doing wrong?
回答1:
According to the XCode Release Notes for Beta 4 the downcast should work now:
Objects of a class type, such as NSObject or NSArray, can now be downcast to bridged Swift types.
(Haven't tried that though)
However, you can cast the objects in your tasks array when you need them:
tasks = managedObjectContext.executeFetchRequest(fetchRequest, error: &error) // array of NSManagedObjects
for obj in tasks {
let task = obj as Task
...
}
回答2:
You have to add the module or app name to the class name in the model editor:
MyApp.Task
This has to be done after you generate the class file, otherwise that part fails. I consider this a bug in the current beta, and have raised it as such.
My previous answer stated to use the @objc decorator, which also works, but the above solution is documented in the swift / cocoa reference.
来源:https://stackoverflow.com/questions/24926418/swift-array-cannot-be-downcast-to-array-of-derived