我正在尝试按照一些教程创建一个Fetched Results Controller。但是在Swift 3中我得到的错误是无法推断出复杂的闭包类型'尝试在下面看到的模式中创建一个。
class FriendsController: UICollectionViewController {
lazy var fetchedResultsController: NSFetchedResultsController = {
let context = (UIApplication.shared.delegate as!
AppDelegate).persistentContainer.viewContext
let fetchRequest: NSFetchRequest = Friend.fetchRequest()
let fetchedResultsController =
NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: context, sectionNameKeyPath: nil, cacheName:
nil)
return fetchedResultsController
}()
我在制作视图,按钮等其他东西时会使用这种闭合模式,但它不起作用(即使我不使用lazy var)。这个错误对我来说也不是很清楚(如上所述)。谢谢。
答案 0 :(得分:2)
NSFetchedResultsController
在Swift 3中是通用的。您必须指定具体类型,因为编译器无法推断出复杂的闭包类型:
lazy var fetchedResultsController: NSFetchedResultsController<Friend> = { ...
答案 1 :(得分:1)
因为您应该指定FetchedResultsControllers所拥有的对象的泛型类型
lazy var fetchedResultsController: NSFetchedResultsController<Friend> = {
let context = //your context
let req = // your request
let fetchedResultsController = NSFetchedResultsController(fetchRequest: req, managedObjectContext:context, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultsController.delegate = self
do {
try fetchedResultsController.performFetch()
}
catch {
print("fetch error \(error)")
}
return fetchedResultsController
}()