问题
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