带有通用 NSFetchRequest 的通用 NSFetchedResultsController 导致错误

Generic NSFetchedResultsController with generic NSFetchRequest results in an error

当尝试设置通用的获取结果控制器时,我在初始化控制器时得到 Cannot convert value of type 'NSFetchRequest<T>' to expected argument type 'NSFetchRequest<_>', Insert ' as! NSFetchRequest<_>

fileprivate var fetchedResultsController: NSFetchedResultsController<T>!

    guard let request: NSFetchRequest<T> = T.fetchRequest() as? NSFetchRequest<T> else {
        assertionFailure("Can't set up NSFetchRequest")
        return
    }
    request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
    fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: dataStore.viewContext, sectionNameKeyPath: nil, cacheName: nil)
    do {
        try fetchedResultsController.performFetch()
    } catch let error {
        DDLogError("Error fetching entities: \(error)")
    }

有人知道这里发生了什么吗?

对于 FRC,您应该明确指定它的类型为 T。

此外,您的代码片段中没有足够的上下文,因此不清楚您是如何定义此 class。然而,我认为它应该是这样的:

import CoreData
class Model<T> where T: NSManagedObject {

    fileprivate var context: NSManagedObjectContext! // assume that somewhere during initialization we setting context

    fileprivate lazy var fetchedResultscontroller: NSFetchedResultsController<T> = { [weak self] in
        guard let this = self else {
            fatalError("lazy property has been called after object has been descructed")
        }
        guard let request = T.fetchRequest() as? NSFetchRequest<T> else {
            fatalError("Can't set up NSFetchRequest")
        }

        request.sortDescriptors = [NSSortDescriptor(key: "key", ascending: true)]
        let tmp = NSFetchedResultsController<T>(fetchRequest: request, managedObjectContext: this.context, sectionNameKeyPath: nil, cacheName: nil)
        return tmp
    }()
}