Reputation: 1084
I used below code fetch the list of Article
from core data and it is giving me the expected result.
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)")
}
Output : 376
But when I am trying to fetch with NSFetchedResultsController. The fetchedObjects always returning nil. I used below code.
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>
}()
The quotes
is always nil. I am not able to figure out what is the problem?
Upvotes: 2
Views: 697
Reputation: 175
try calling performFetch() on fetchedResultsController outside the closure.
hope that will work.
Upvotes: 1