So instead you can leverage Swift's support for generics like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | func fetch<T: NSManagedObject>(entityType: T.Type, fromManagedObjectContext moc: NSManagedObjectContext) -> [T] { var results = [T]() let classNameComponents: [String] = entityType.description().components(separatedBy: ".") let className = classNameComponents[classNameComponents.count-1] let fetchRequest = NSFetchRequest<T>(entityName: className) do { results = try moc.fetch(fetchRequest) } catch { print("Error on GetSite: \(error)") } return results } |
One thing to note is that generic methods typically take arguments that are instances of the types for which they are defined. But in this case we want to be able to simply use a class name in the parameter list because it's more clear that way. So the parameter entityType is actually of type T.Type. And the way we enter the argument for entityType is
So hopefully this will make my Core Data unit testing less painful.
No comments:
Post a Comment