我想在我的代码中使用fetchedResultsController
和Swift3。我试过this way和其他方式,但我无法做到。这是我的代码(它不起作用):
var fetchedResultsController: NSFetchedResultsController<Entity> {
let fetchRequest: NSFetchRequest<Entity>
if #available(iOS 10.0, *) {
fetchRequest = Entity.fetchRequest()
} else {
// Fallback on earlier versions
fetchRequest = NSFetchRequest(entityName: "Entity")
}
fetchRequest.fetchBatchSize = 20
let orderDescriptor = NSSortDescriptor(key: "archiveOrder", ascending: true)
let nameDesctiptor = NSSortDescriptor(key: "entityName", ascending: false)
fetchRequest.sortDescriptors = [orderDescriptor, nameDesctiptor]
let aFetchedResultsController: NSFetchedResultsController<Entity> = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: appDelegate.managedObjectContext, sectionNameKeyPath: nil, cacheName: "Master")
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
do {
try _FetchedResultsController.performFetch()
} catch {
let nserror = error as NSError
print("Unresolved error \(nserror), \(nserror.userInfo)")
}
return _FetchedResultsController!
}
你能给我任何意见或建议吗?
答案 0 :(得分:0)
Apple基本上建议使用一个只在闭包中运行一次代码的闭包将NSFetchedResultsController
声明为非可选的延迟初始化属性。
lazy var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> = { ... }()
您的代码无法编译,因为Swift代码区分大小写,这意味着_fetchedResultsController
和_FetchedResultsController
是两个不同的东西。
其余代码似乎是正确的。
lazy var fetchedResultsController: NSFetchedResultsController<Entity> = {
let fetchRequest: NSFetchRequest<Entity>
if #available(iOS 10.0, *) {
fetchRequest = Entity.fetchRequest()
} else {
// Fallback on earlier versions
fetchRequest = NSFetchRequest(entityName: "Entity")
}
fetchRequest.fetchBatchSize = 20
let orderDescriptor = NSSortDescriptor(key: "archiveOrder", ascending: true)
let nameDesctiptor = NSSortDescriptor(key: "entityName", ascending: false)
fetchRequest.sortDescriptors = [orderDescriptor, nameDesctiptor]
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: appDelegate.managedObjectContext,
sectionNameKeyPath: nil,
cacheName: "Master")
aFetchedResultsController.delegate = self
do {
try aFetchedResultsController.performFetch()
} catch {
let nserror = error as NSError
print("Unresolved error \(nserror), \(nserror.userInfo)")
}
return aFetchedResultsController
}()