懒惰的 var NSFetchedResultsController 在 Swift 3.0 中产生错误 [英] lazy var NSFetchedResultsController producing error in Swift 3.0

查看:60
本文介绍了懒惰的 var NSFetchedResultsController 在 Swift 3.0 中产生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚将我的项目迁移到 Swift 3,但我的懒惰实例化 NSFetchResultController 遇到了一个错误.我在这里使用这种方法:

这个方法在 Swift 3 下不再可行了吗?我尝试添加 () -><<错误类型>>在 按照 Xcode 的建议,但未能产生正确的结果.

解决方案

建议的 () -><<错误类型>> 具有误导性.

在 Swift 3 中 NSFetchedResultsController 已经成为一个泛型类型.你必须初始化它:

lazy var fetchedResultsController: NSFetchedResultsController= {...}()

以及NSFetchRequest

let fetchRequest = NSFetchRequest(entityName: "MyEntity")

<小时>

如果你使用的是 NSManagedObject 的子类——推荐——你可以使用子类类型来更具体

lazy var fetchedResultsController: NSFetchedResultsController= {....让 fetchRequest = NSFetchRequest(entityName: "MyEntity")

巨大的好处是您可以使用 fetchinsert 等摆脱所有类型转换.

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.

解决方案

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.

这篇关于懒惰的 var NSFetchedResultsController 在 Swift 3.0 中产生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆