Update Collection View after saving a new entity to Core Data

262 views Asked by At

I am having difficulties updating the collection view, after saving new entity object to persisentContainer. I have to reload the application to see the new data. Ive read similar questions, but they don't appear to be having the same issue that i'm having, since they are able to call reloadData with out any problem.

Code Overflow popalert requesting user name save info into core data entity insert new section in collection view

Basically simplified scheme of what i'm trying to achieve. However, after i save the record, and i attempt to insert a new section with performBatchupdate i get same number of records. I've looked at the values through the cycle and im stuck between two probable causes. The first, my fetch request is not getting new data. Or, the context is not being saved until the application restarts. On restart the new data is loaded, however this is not the case when i push it to background and reopen it.

Below is general code. Looking for any suggestions, or to let me know what i'm missing.

class CoreDataUpdateCollectionView {
    
    var name: String!
    var persistentContainer: NSPersistentContainer!
    
    var users: Users! // Entity fetch request
    // users = fetchRequestController
    have also used fetchRequestController directly
    
    func save(entity: Entity) {
        
        entity.name = name
        
        save(context: persistentContainer)
        
        insertSection()
    }
    
    func save(context: NSPersistentContainer) {
        
        // have also attempted performAndWait
        // assuming that it would run code after block was completed
        context.viewContext.perform {
            try context.viewContext.save()
        } catch {
            print(error)
        }
    }
    
    // I've attempted to wrap this around a DispatchQueue.main.async{}
    // still not reloading since the issue appears to be coming from the persistent store
    func insertSection() {
        
        collectionView.performBatchUpdates {
            // replaced with, collectionView.reloadData() nothing appears to happen in view
            collectionView.insertSection()
        } , { finished in
            // toggled on and off
            collectionView.reloadData()
        }
    }
    
    // DataSource Delegate
    func collectionView(_ collectionView: UICollectionView, numOfItemsIn section: Int) -> {
        // users retur the same number
        return users.count
    }
    
    
    // fetch request controller
    lazy var fetchUserController: NSFetchRequestResult<User> = {
        let fetchRequest: NSFetchRequest<User> = User.fetchRequest()
        fetchRequest.returnsObjectsAsFaults = false
        fetchRequest.sortDescriptors = [
            NSSortDescriptor(key: "name", ascending: true)
        ]
        fetchRequest.relationshipKeyPathsForPrefetching = [
            "friends"
        ]
        
        let controller = NSFetchedResultsController(
            fetchRequest: fetchRequest,
            managedObjectContext: persistentContainer.viewContext, sectionNameKeyPath: "name",
            cacheName: nil
        )
        
        controller.delegate = self

        do {
            try controller.performFetch()
        } catch {
            fatalError("###\(#function): Failed to performFetch: \(error)")
        }
        
        return controller
    }()
}
0

There are 0 answers