I want to use new Core Data API introduced in iOS10.
@available(iOS 10.0, *)
open class func fetchRequest() -> NSFetchRequest<NSFetchRequestResult>
I created generic function to fetching all kinds of objects:
func getAllEntities<T: NSManagedObject>(ofType type: T.Type, success: @escaping ([T]) -> ()) throws -> [T] {
let fetchRequest: NSFetchRequest<T> = T.fetchRequest()
let asyncFetchRequest = NSAsynchronousFetchResult(fetchRequest: fetchRequest) { result in
success(result.finalResult ?? [])
}
try databaseStack.persistentContainer.viewContext.execute(asyncFetchRequest)
}
but in line let fetchRequest: NSFetchRequest<T> = T.fetchRequest()
I got issue:
Cannot convert value of type
'NSFetchRequest<NSFetchRequestResult>'
to specified type'NSFetchRequest<T>'
What did I do wrong?
T.fetchRequest()
returns a NSFetchRequest<NSFetchRequestResult>
,
you have to explicitly cast it to the specific NSFetchRequest<T>
:
let fetchRequest = T.fetchRequest() as! NSFetchRequest<T>
let asyncFetchRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { result in
success(result.finalResult ?? [])
}
Try either one of these.
One: I experienced something similar in my project.
I found that there were problems with the auto generated headers of Core Data entities. Try deleting from:
/Users/**user**/Library/Developer/Xcode/DerivedData/**AppName**/Build/Intermediates/**AppName**/Debug-iphonesimulator/**AppName**.build/DerivedSources/CoreDataGenerated
then clean your project with
command+shift+K
Then try building.
Two:
Try using let fetchRequest = NSFetchRequest<T>(entityName: NSStringFromClass(T.self))
Swifty style of 2nd approach, works 100%:
let fetchRequest = NSFetchRequest<T>(entityName: String(describing: T.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