NSFetchedResultsController不返回任何结果

时间:2017-07-22 13:27:05

标签: ios core-data swift3 nsfetchedresultscontroller

我正在尝试使用NSFetchedResultsController从CoreData中获取记录

我使用以下代码:

let fetchedResultsController: NSFetchedResultsController<Appointment> = {
    let fetchRequest = NSFetchRequest<Appointment>(entityName: "Appointment")
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
    let moc:NSManagedObjectContext = CoreDataManager.managedObjectContext
    let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: nil)
    return frc 
}()

numberOfItemsInSection委托中我定义了

if let count = fetchedResultsController.sections?[0].numberOfObjects {
    return count
}
return 0

最后在cellForItemAt委托方法中,我已经定义了

let appointment = self.fetchedResultsController.object(at: indexPath)

问题是,它是否显示核心数据中的任何记录。它也没有显示任何错误。这个清单是空的。

如果我使用以下代码获取记录,则可以正常工作。

public func fetchAppointmentList() -> [Appointment] {
    var list:[Appointment] = []
    let request: NSFetchRequest<Appointment> = Appointment.fetchRequest()
    do {
        list = try moc.fetch(request)
    } catch {
        fatalError("\(error)")
    }
    return list
}
override func viewDidLoad() {
    super.viewDidLoad()
    self.appointmentList = self.fetchAppointmentList()
}
// Removed rest of the code to keep it simple.

为什么我的fetchedResultsController无效?

感谢。

1 个答案:

答案 0 :(得分:1)

好的,我忘了在performFetch()中致电viewDidLoad(),在viewDidLoad中定义以下代码解决了我的问题。

do {
    try fetchedResultsController.performFetch()
} catch {
    print("An error occurred")
}