我使用下面的代码从核心数据中获取Article
的列表,它给了我预期的结果。
let moc = CoreDataHelper().backgroundContext
let employeesFetch = NSFetchRequest<NSFetchRequestResult>(entityName:"Article")
do {
let fetchedEmployees = try moc?.fetch(employeesFetch) as! [Article]
print(fetchedEmployees.count)
} catch {
fatalError("Failed to fetch employees: \(error)")
}
输出:376
但是当我尝试使用NSFetchedResultsController进行提取时。 fetchedObjects总是返回nil。我使用下面的代码。
fileprivate lazy var fetchedResultsController: NSFetchedResultsController<Article> = {
// Create Fetch Request
let moc = CoreDataHelper().backgroundContext
// let fetchRequest: NSFetchRequest<Article> = Article.fetchRequest()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"Article")
// Configure Fetch Request
fetchRequest.sortDescriptors = [NSSortDescriptor(key:"category", ascending: true)]
// Create Fetched Results Controller
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext:moc!, sectionNameKeyPath: nil, cacheName: nil)
// Configure Fetched Results Controller
fetchedResultsController.delegate = self
let quotes = fetchedResultsController.fetchedObjects
return fetchedResultsController as! NSFetchedResultsController<Article>
}()
quotes
始终为零。我无法弄清楚问题是什么?
答案 0 :(得分:0)
尝试在封包外部的fetchedResultsController上调用performFetch()。
希望能奏效。