我使用以下代码从核心数据实体One中获取数据:
func fetchDataOne() {
let fetchRequest: NSFetchRequest<One> = One.fetchRequest()
do {
fetchRequest.predicate = NSPredicate(format: "questionWasShown == %@", NSNumber(value: false))
// Save result to result array
let result = try PersistentService.context.fetch(fetchRequest)
if result.count > 0 {
// do some stuff
}
}
我计划添加更多实体(20-30)。维持30个不同的提取请求将很困难。我要重写这一行
let fetchRequest: NSFetchRequest<One> = One.fetchRequest()
以便我可以使用通用代码。我想实现这样的目标
func fetchData(entity: T) {
...
let fetchRequest: NSFetchRequest<T> = T.fetchRequest()
...
}
核心数据中可能吗?
答案 0 :(得分:1)
正如Ryan在上面的评论中所述,您必须让编译器知道T具有fetchRequest方法,如下所示:
func fetchData<T:NSManagedObject>(entity: T.Type) {
let fetchRequest = T.fetchRequest()
do {
fetchRequest.predicate = NSPredicate(format: "questionWasShown == %@", NSNumber(value: false))
let result = try CoreDataHelper.managedObjectContext.fetch(fetchRequest)
if result.count > 0 {
// do some stuff
}
} catch {
}
}
用法:
self.fetchData(entity: One.self)