Jason C. Howlin Jason C. Howlin - 1 year ago 2225
Swift Question

How to initialize a NSFetchedResultsController in iOS 10 Swift 3

I can't get my NSFetchedResultsController initialized in iOS 10 using Swift 3.

let request = NSFetchRequest<NasaPicture>(entityName:"NasaPicture")
request.predicate = Predicate(format: "isPagedResult == YES")
request.sortDescriptors = [SortDescriptor(key: "date", ascending: false)]
fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: nil)

Compiler is complaining that

"Cannot convert value of type NSFetchedResultsController<NasaPicture> to expected type NSFetchedResultsController<_>"

The controller is now using generic type for swift, but it is not inferring the entity type correctly. I've tried explicitly:

fetchedResultsController = NSFetchedResultsController<NasaPicture>(fetchRequest: request, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: nil)

No luck either.


Answer Source

NSFetchRequest is now a generic. NSFetchedResultsController is a generic too. Therefore, when declaring variables, you have to use a generic declaration, e.g.:

var fetchedResultsController: NSFetchedResultsController<NasaPicture>?
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download