Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert value of type 'NSFetchRequest<NSFetchRequestResult>' to specified type 'NSFetchRequest<T>'

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?

like image 590
Kamil Harasimowicz Avatar asked Jan 05 '18 14:01

Kamil Harasimowicz


2 Answers

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 ?? [])
}
like image 86
Martin R Avatar answered Nov 02 '22 17:11

Martin R


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))
like image 36
Niall Kiddle Avatar answered Nov 02 '22 19:11

Niall Kiddle