将新实体保存到 Core Data 后更新集合视图

问题描述

在将新实体对象保存到persistentContainer 后,我在更新集合视图时遇到了困难。我必须重新加载应用程序才能看到新数据。我读过类似的问题,但他们似乎没有遇到与我相同的问题,因为他们能够毫无问题地调用 reloadData。

代码溢出 popalert 请求用户名 将信息保存到核心数据实体中 在集合视图中插入新部分

我试图实现的基本简化方案。但是,在我保存记录并尝试使用 performBatchupdate 插入一个新部分后,我得到了相同数量的记录。我已经查看了整个周期的值,但我陷入了两个可能的原因之间。首先,我的获取请求没有获取新数据。或者,在应用程序重新启动之前不会保存上下文。重新启动时会加载新数据,但是当我将其推送到后台并重新打开时,情况并非如此。

以下是通用代码。寻找任何建议,或者让我知道我缺少什么。

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
    }()
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)