警告:我对 Swift和Core Data都很陌生 我的代码中有几个函数返回特定实体类型的数组: func fetchStores() - [Store]? { var stores: [Store]? let fetchRequest: NSFetchRequestStore = Store.fetchRequest() do { stores =
我的代码中有几个函数返回特定实体类型的数组:
func fetchStores() -> [Store]? { var stores: [Store]? let fetchRequest: NSFetchRequest<Store> = Store.fetchRequest() do { stores = try ad.persistentContainer.viewContext.fetch(fetchRequest) } catch { assert(false, error.localizedDescription) } return stores }
我想创建一个处理所有实体的泛型函数:
func fetchEntities<T: NSManagedObject>(entity: T) -> [T]? { var results: [T]? if let fetchRequest: NSFetchRequest<T> = T.fetchRequest() as? NSFetchRequest<T> { do { results = try ad.persistentContainer.viewContext.fetch(fetchRequest) } catch { assert(false, error.localizedDescription) } } else { assert(false,"Error: cast to NSFetchRequest<T> failed") } return results } // Usage: let store = Store() let stores = fetchEntities(entity: store)
有没有办法让我这样做而无需创建Store实例?
TIA
你快到了.您只需要更改参数从T到T的类型:
func fetchEntities<T: NSManagedObject>(entity: T.Type) -> [T]?
这样你就可以传递一个类型而不是一个实例:
let stores = fetchEntities(entity: Store.self)