I'm confused about generics here. The static keyword is making it difficult for me to understand.
import CoreData
@objc(Performer)
public class Performer: NSManagedObject, Fetchable {
@NSManaged public var dob: Date
@NSManaged public var firstName: String
@NSManaged public var lastName: String
}
protocol Fetchable {
static func fetchAll<T: NSManagedObject>(withPredicate predicate: NSPredicate?, in context: NSManagedObjectContext) throws -> [T]
}
extension Fetchable {
static func fetchAll<T: NSManagedObject>(withPredicate predicate: NSPredicate?, in context: NSManagedObjectContext) throws -> [T] {
let entityName = String(describing: self)
let request = NSFetchRequest<T>(entityName: entityName)
request.predicate = predicate
return try context.fetch(request)
}
}
let performers: [NSManagedObject] = try! Performer.fetchAll(in: context)
//Or
let performers: [Performer] = try! Performer.fetchAll(in: context) as! [Performer]
//Or
EDIT: This line was focus of my question as it was throwing an error. But fixed it by killing Xcode and re-launching.
let performers: [Performer] = try! Performer.fetchAll(in: context)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…