【问题标题】:NSFetchedResultsController does not return any resultNSFetchedResultsController 不返回任何结果
【发布时间】:2017-12-28 12:49:37
【问题描述】:

我正在尝试使用 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 不工作?

谢谢。

【问题讨论】:

    标签: ios core-data swift3 nsfetchedresultscontroller


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-12-09
      • 2020-10-03
      • 2017-03-19
      • 2017-05-20
      • 2012-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多