首页 > 解决方案 > 从核心数据加载数据以显示在集合视图上

问题描述

我有两个视图控制器(vc1 和 vc2)。在 vcTwo 上,当我添加游戏时,我使用核心数据保存项目。该项目应立即从集合视图显示在 vcOne 上。但是即使使用 .collection 视图也不会立即加载数据collectionView.reloadData。我必须重新启动应用程序才能在集合视图中查看最后添加的项目。我怎么能让它发生。

var game: GameMo?
var gamesMo: [GameMo]? = []
var fetchRequestController : NSFetchedResultsController<GameMo>!

extension ViewControllerOne: NSFetchedResultsControllerDelegate {

    func fetechRequest (){
        let fetchRequest = NSFetchRequest<GameMo>(entityName: "Game")

      fetchRequest.sortDescriptors = [NSSortDescriptor(key: "win", ascending: true)]

       if let appDelegate = (UIApplication.shared.delegate as? AppDelegate){
            let context = appDelegate.persistentContainer.viewContext

            // fetch result controller
            fetchRequestController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
            fetchRequestController.delegate = self

            do{
                try fetchRequestController.performFetch()

                if let fetchedObjects = fetchRequestController.fetchedObjects {
                    gamesMo = fetchedObjects


                    print(fetchRequest)
                }
            }catch{
                fatalError("Failed to fetch entities: \(error)")
            }
        }

    } 

视图控制器一

class ViewControllerTwo: UIViewController {
     var game: GameMo?
       func saveToCoreData(){
            guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
            game = GameMo(context: appDelegate.persistentContainer.viewContext)
            game?.gameOutcome = gameOutcome.text
            game?.goal = Int32(goal.text ?? "0") ?? 0
            game?.rivalGoal = Int32(rivalGoal.text ?? "0") ?? 0
    print("Saving data")
            appDelegate.saveContext()
            delegate?.reloadCollectionViewData()
        }
}

标签: iosswiftcore-data

解决方案


您应该在VC2的函数fetchRequest()行之后调用 VC1 。appDelegate.saveContext()saveToCoreData()


推荐阅读