无法转换'NSFetchRequest类型的值 '到指定类型'NSFetchRequest “

问题描述 投票:4回答:2

我想使用iOS10中引入的新Core Data API。

@available(iOS 10.0, *)
open class func fetchRequest() -> NSFetchRequest<NSFetchRequestResult>

我创建了通用函数来获取各种对象:

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)
}

但在排队let fetchRequest: NSFetchRequest<T> = T.fetchRequest()我遇到了问题:

无法将'NSFetchRequest<NSFetchRequestResult>'类型的值转换为指定类型'NSFetchRequest<T>'

我做错了什么?

ios swift core-data ios10
2个回答
3
投票

T.fetchRequest()返回NSFetchRequest<NSFetchRequestResult>,你必须明确地将它投射到特定的NSFetchRequest<T>

let fetchRequest = T.fetchRequest() as! NSFetchRequest<T>
let asyncFetchRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { result in
    success(result.finalResult ?? [])
}

2
投票

尝试其中任何一个。

一:我在项目中经历过类似的事情。

我发现自动生成的Core Data实体头部存在问题。尝试删除:

/Users/**user**/Library/Developer/Xcode/DerivedData/**AppName**/Build/Intermediates/**AppName**/Debug-iphonesimulator/**AppName**.build/DerivedSources/CoreDataGenerated

然后用command+shift+K清理你的项目

然后尝试建设。

二:尝试使用let fetchRequest = NSFetchRequest<T>(entityName: NSStringFromClass(T.self))

第二种方式的Swifty风格,100%工作:

let fetchRequest = NSFetchRequest<T>(entityName: String(describing: T.self))
© www.soinside.com 2019 - 2024. All rights reserved.