首页 文章

NSFetchedResultsController(Core Data)不提供正确的数据源表视图控制器

提问于
浏览
2

我最近遇到了一个挑战 . 我真的很感激任何人都可以提供任何支持 .

The issue: NSFetchedResultsController (Core Data) does NOT provide correct data source Table View Controller.

What I am trying to achieve:

  • 我使用CloudKit作为存储大部分用户数据的主数据库 .

  • 我使用Core Data在本地存储CKRecordID和recordChangeTag,以更新Table View和Collection View,并将这些存储值作为获取相关CloudKit数据的句柄 .

  • 我创建了一个NSFetchedResultsController作为表视图控制器的实例变量,以获取数据结果作为表视图的数据源 .

What works:

  • CloudKit数据库可以通过应用程序保存,修改和删除CKRecord .

  • 如果不使用Core Data NSFetchedResultsController,其中只有CloudKit和Table View位于项目的最后一个版本中,该应用程序可以加载CloudKit数据,以通过CloudKit方便的API将表视图作为其数据源提供 . 数据修改和删除也有效 .

What error do I get:

  • 现在我有CloudKit,Core Data和Table View Controller的实例变量NSFetchedResultsController,当我试图将新对象添加到Core Data数据库并插入新的Table View行时,控制台和app中会打印以下错误崩溃:

  • timicip_APITest_CloudKit_TableView_StoringRecordID [37142:1567814] ***由于未捕获的异常终止应用'NSInternalInconsistencyException',原因:'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (0) must be equal to the number of rows contained in that section before the update (0), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).' *

What have I done that does not work:

  • 我尝试通过每次向数据库中插入新数据时调用managedObjectContext.save()来确保将新对象保存到Core Data托管持久存储中 . 但即使在我完成之后,我们表视图也试图从NSFetchedResultsController获取数据,NSFetchedResultsController将不会在表视图数据源方法"tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int"中提供正确数量的其获取对象 . 应用程序崩溃了 . 但是当我重新打开应用程序时,我在上次打开时输入的数据将显示在表视图中,而当我向表视图添加新对象时,它仍然会崩溃 .

What do I think the direction of the solution:

  • 我不确定"managedObjectContext.save()"调用是否真的保存了数据,也不确定是否使用"NSFetchedResultsController.sections![section].numberOfObjects"返回保存的对象 .

  • 我是否需要通过调用结果"executeFetchRequest:error: on the NSManagedObjectContext"从数据库创建新的获取请求,但是如果使用此方法,那么拥有专为Table View设计的NSFetchedResultsController有什么意义呢 .

  • "insertRowsAtIndexPaths(indexPaths: [NSIndexPath], withRowAnimation animation: UITableViewRowAnimation)"是否需要任何支持代码以确保使用更正的indexPath更新表视图?

Summary:

我想知道如何克服打印错误,以便我可以在表视图中添加一个新行,其中Core Data数据库从managedObjectContext中提供适量的对象 .

Solution:

实现NSFetchedResultsControllerDelegate,让它完全控制表视图的CRUD流,而不是调用常规表视图行插入,删除NSFetchedResultsControllerDelegate'方法之外的方法,因为Core Data的NSFetchedResultsController充当数据源 .

非常感谢

问候,

张靖元(Jingyuan Knight Zhang)

1 回答

  • 3

    解:

    实现NSFetchedResultsControllerDelegate,让它完全控制表视图的CRUD流,而不是调用常规表视图行插入,删除NSFetchedResultsControllerDelegate'方法之外的方法,因为Core Data的NSFetchedResultsController充当数据源 .

相关问题