ios - 从核心数据加载数据以显示在集合视图上
问题描述
我有两个视图控制器(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()
}
}
解决方案
您应该在VC2的函数fetchRequest()
行之后调用 VC1 。appDelegate.saveContext()
saveToCoreData()
推荐阅读
- javascript - 打印函数返回错误 elem.cloneNode 不是函数
- r - R:使用条件根据数据框 Y 中的值替换数据框 X 中的值
- python - 使用 React Proxy 显示 Flask 数据
- java - 如何在 java 中使用 Math.random() 每行打印 10 个数字?
- sql - 我如何求和,直到它满足一个标准?
- python - 在图像中绘制隐式函数(Python,[OpenCV])
- c# - 平面数据只保存最后一个对象在最后
- javascript - 是否可以将“id”属性的值传递给 React 中的 onClick 属性中传递的函数?
- supercollider - 超级对撞机中的迭代
- jenkins - 在 groovy jenkinsfile 中获取当前月份