Search code examples
iosswiftcore-datansfetchedresultscontroller

NSFetchedResultsController -[__NSArrayM insertObject:atIndex:]: object cannot be nil


I've done quite a bit of research on this issue, but found nothing that lead me to a solution. I am attempting to use NSFetchedResultsController, and getting this error when I run the app:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[__NSArrayM insertObject:atIndex:]: object cannot be nil' *** First throw call stack:

I have found that some people encountered this problem when using the estimatedHeightForRowAtIndexPath method, but I'm not using it.

Using an Exception Breakpoint revealed it's crashing at this line in the below block of code: let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedContext, sectionNameKeyPath: "date.theDate", cacheName: nil). It doesn't make it past here.

I have a print statement below it that never executes. The managedObjectContext does exist. frc is called for the first time in viewDidLoad (code below). I'll also include my AppDelegate code.

Thanks in advance!

Here's my relevant code:

import UIKit
import CoreData

class TransactionsViewController: UIViewController, UITableViewDataSource, NSFetchedResultsControllerDelegate {

    var containerDelegate: ContainerDelegate?

    var managedContext: NSManagedObjectContext!

    lazy var frc: NSFetchedResultsController = {
        // Initialize Fetch Request
        let fetchRequest = NSFetchRequest(entityName: "DailyTransactions")

        // Initialize Fetched Results Controller
        let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedContext, sectionNameKeyPath: "date.theDate", cacheName: nil)

        print("Assigned frc complete.")

        // Configure Fetched Results Controller
        frc.delegate = self

        print("FRC finished")

        return frc
    }()

frc is first used in viewDidLoad by this:

    // Exectue Fetch Request
    do {
        try self.frc.performFetch()
    } catch {
        let fetchError = error as NSError
        print("\(fetchError), \(fetchError.userInfo)")
    }

UPDATE:

After using sort descriptions on the Fetch Request and changed the section key path the nil, I resolved this issue. I can even change section key path back to date.theDate and it will run fine.


Solution

  • After using sort descriptions on the Fetch Request and changing the section key path to nil, I resolved this issue. I can even change section key path back to date.theDate and it will run fine. My mistake was either somewhere else or somehow associated with Section key path.