ioscore-datansfetchedresultscontroller

NSFetchedResultsController always including temporary objects


I have a NSFetchedResultsController that I set up as following:

        let fetchRequest = NSFetchRequest(entityName: "Order")
        fetchRequest.includesPendingChanges = false
        fetchRequest.sortDescriptors = [
            NSSortDescriptor(key: "status", ascending: false),
            NSSortDescriptor(key: "date", ascending: false)]

        self.fetchedResultsController = NSFetchedResultsController(
            fetchRequest: fetchRequest,
            managedObjectContext: DataStoreManager.sharedInstance.mainContext,
            sectionNameKeyPath: "section",
            cacheName: nil)

        do {
            try self.fetchedResultsController.performFetch()

        } catch let error as NSError {
            print(error)
        }

The problem is even with the includesPendingChanges set to false, it stills calls controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) every time I create a new object in the context (without saving).

Is there something else I should look for to avoid this situation?


Solution

  • The recommended way is to use a child context. The parent should be the main thread managed object context used in the fetched results controller.

    If you save, the changes are immediately "pushed" to the main context, i.e. the fetched results controller. (Save the main context to persist to the persistent store.)

    If you don't want to save, just discard the child context without saving. The fetched results controller will never know about it.