0

在将新实体对象保存到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
    }()
}
4

0 回答 0