Search code examples
iosswiftcore-datansmanagedobjectcontextnsfetchrequest

An instance of NSFetchedResultsController requires a non-nil fetchRequest and managedObjectContext'


Other people have asked a similar question, but the answers given did not help me. I am trying to create a table view with core data and I keep getting an error message that my fetchRequest and/or managedObjectContext are nil

class CustomTableViewController: UITableViewController, 
NSFetchedResultsControllerDelegate {

var coreDataContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext


@available(iOS 10.0, *)
fileprivate lazy var fetchedResultsController: NSFetchedResultsController<Movie> = {
    // Initiate the query
    let fetchRequest: NSFetchRequest<Movie> = Movie.fetchRequest() as! NSFetchRequest<Movie>

    // Sort the data
    fetchRequest.sortDescriptors = [NSSortDescriptor(key:"title", ascending: true)]

  NSLog("Request: %@, Context: %@", fetchRequest, self.coreDataContext);        
  let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.coreDataContext, sectionNameKeyPath: nil, cacheName: nil)

    fetchedResultsController.delegate = self
    return fetchedResultsController
}()


override func viewDidLoad() {
    super.viewDidLoad()

    navigationController?.setToolbarHidden(false, animated: false)

    do {
        // when view loads, run the fetch (query)
        if #available(iOS 10.0, *) {
            try self.fetchedResultsController.performFetch()
        } else {
            // Fallback on earlier versions
        }
    } catch {
        let fetchError = error as NSError
        print("Unable to Perform Fetch Request")
        print("\(fetchError)")
    }
    }

Does anyone have any ideas what's wrong? Also, not sure if it matters, but my project is a mix of both Objective-C and Swift

Also, the NSLog("Request: %@, Context: %@", fetchRequest, self.coreDataContext) from my above code prints out:

Request: (null), Context: <NSManagedObjectContext: 0x1701db4e0>

I have an entity called Movie in my xcdatamodeld with three String attributes. I also created a class for Movie like this in its own Movie.swift file:

import UIKit
import CoreData

class Movie: NSManagedObject {

}

Solution

  • The problem is that your Movie class has no code for generating a fetch request.

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Movie> {
        return NSFetchRequest<Movie>(entityName: "Movie");
    }
    

    The solution: Delete your Movie class file entirely.

    In the data model, configure your Movie entity to do automatic code generation:

    enter image description here

    That will solve the problem. Xcode knows how to make the class files for an entity. So just permit it to do so, and all will be well.