Search code examples
iosswiftcore-datansfetchedresultscontroller

fetchResultController get NSInvalidArgumentException swift


basically i want to fetch all object in that entity i'm calling this method in viewDidLoad()

func updateUI() {
    if let context = container?.viewContext {
        let request:NSFetchRequest<Reminder> = Reminder.fetchRequest()
        request.sortDescriptors = [NSSortDescriptor(key: title, ascending: true)]
        fetchResultController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
        try? fetchResultController?.performFetch()
        remindersCollectionViewController.reloadData()
    }
}

title is String? entity name is "Reminder" currently no object in coredata

when excute this line of code

fetchResultController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)

the app crashes and i got the error

2018-06-13 12:14:25.345072+0800 Reminders[25712:3061130] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'

appreciated any help


Solution

  • What looks odd here is that title is a String? in your sort descriptor. In most use cases the sort descriptor is fixed so you should do (assuming there is an attribute title for Reminder)

    request.sortDescriptors = [NSSortDescriptor(key: "title", ascending: true)]
    

    or even better, use #keyPath

    request.sortDescriptors = [NSSortDescriptor(key: #keyPath(Reminder.title), ascending: true)]
    

    If I am wrong and title is a variable that can change between fetches then at least unwrap it before using it

    if let sortKey = title {
         request.sortDescriptors...
    }