微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决将新实体保存到 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 举报,一经查实,本站将立刻删除。