lazy var NSFetchedResultsController producing error in Swift 3.0

这一生的挚爱 提交于 2019-12-12 13:50:23

问题


I just migrated my project to Swift 3 and am stuck on an error for my lazy instantiated NSFetchResultController. I use this method here :

https://www.andrewcbancroft.com/2015/03/05/displaying-data-with-nsfetchedresultscontroller-and-swift/

My current code

lazy var fetchedResultsController: NSFetchedResultsController = {

    let primarySortDescriptor = NSSortDescriptor(key: "company", ascending: true)
    let sortDescriptors = [primarySortDescriptor]

    self.fetchRequest.sortDescriptors = sortDescriptors

    let frc = NSFetchedResultsController(
        fetchRequest: self.fetchRequest,
        managedObjectContext: self.managedObjectContext!,
        sectionNameKeyPath: nil,
        cacheName: nil)

    frc.delegate = self

    return frc
}()

It produces 2 errors as shown below

Is this method no longer possible under Swift 3? I tried adding () -> <<error type>> in as suggested by Xcode but failed to produce the correct results.


回答1:


The suggested () -> <<error type>> is misleading.

In Swift 3 NSFetchedResultsController has become a generic type. You have to initialize it:

lazy var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> = {
...
}()

as well as NSFetchRequest

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "MyEntity")

If you are using a subclass of NSManagedObject – which is recommended – you can use the subclass type for being more specific

lazy var fetchedResultsController: NSFetchedResultsController<MyEntity> = {
....
let fetchRequest = NSFetchRequest<MyEntity>(entityName: "MyEntity")

The huge benefit is you get rid of all type casts using fetch, insert etc.



来源:https://stackoverflow.com/questions/39816877/lazy-var-nsfetchedresultscontroller-producing-error-in-swift-3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!