I use following code to fetch data from Core Data entity 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
}
}
I plan to add more entities(20-30). It will be difficult to maintain 30 different fetch requests. I want to rewrite this line
let fetchRequest: NSFetchRequest<One> = One.fetchRequest()
so that i can use generic code. I want to achieve something like that
func fetchData(entity: T) {
...
let fetchRequest: NSFetchRequest<T> = T.fetchRequest()
...
}
It is possible in Core Data?
As Ryan said above in comments, you have to let the compiler know T has the method fetchRequest, like so:
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 {
}
}
Usage:
self.fetchData(entity: One.self)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With