NSFetchedResultsController 没有 return 任何结果
NSFetchedResultsController does not return any result
我正在尝试使用 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 不工作?
谢谢。
好的,我忘记在viewDidLoad()
中调用performFetch()
,在viewDidLoad
中定义以下代码解决了我的问题。
do {
try fetchedResultsController.performFetch()
} catch {
print("An error occurred")
}
我正在尝试使用 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 不工作?
谢谢。
好的,我忘记在viewDidLoad()
中调用performFetch()
,在viewDidLoad
中定义以下代码解决了我的问题。
do {
try fetchedResultsController.performFetch()
} catch {
print("An error occurred")
}