有人知道我怎么能解决这个错误吗?在以下代码块的第一行收到错误:
let fetchedResultsController: NSFetchedResultsController = {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Message")
let delegate = UIApplication.shared.delegate as! AppDelegate
let context = delegate.persistentContainer.viewContext
let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
return frc
}()
答案 0 :(得分:7)
尝试在闭包中添加返回类型,如下代码:
let fetchedResultsController: NSFetchedResultsController = { () -> NSFetchedResultsController<NSFetchRequestResult> in
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Message")
let delegate = UIApplication.shared.delegate as! AppDelegate
let context = delegate.persistentContainer.viewContext
let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
return frc
}()
答案 1 :(得分:3)
错误信息有点误导,问题是你做错了 不指定变量的通用占位符类型。
您可以向闭包添加显式返回类型,如@Mukesh 建议,在这种情况下,变量的类型注释不是 需要:
let fetchedResultsController = { () -> NSFetchedResultsController<NSFetchRequestResult> in
// ...
return frc
}()
或者完全指定变量的类型,然后关闭返回 类型是自动推断的:
let fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> = {
// ...
return frc
}()
答案 2 :(得分:0)
两个问题:
NSManagedObject
子类。 声明NSFetchedResultsController
至少需要一个排序描述符。
let fetchedResultsController: NSFetchedResultsController<Message> = {
let fetchRequest = NSFetchRequest<Message>(entityName: "Message")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "somekey", ascending: true]
let delegate = UIApplication.shared.delegate as! AppDelegate
let context = delegate.persistentContainer.viewContext
let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
return frc
}()