NSFetchResultsController在同时更新两个元素期间抛出错误

时间:2018-02-09 16:53:40

标签: ios core-data nsfetchedresultscontroller

我正在集合视图中尝试两个更新元素。当我只传递一条消息时,它可以正常工作

func simulate() {
    let delegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.persistentContainer.viewContext
   FriendsController.createMessageWithText(text: "Here's a text message that was sent a few minutes ago...", friend: friend!, minutesAgo: 1, context: context)
  //second message  
    FriendsController.createMessageWithText(text: "Another message to give you hard time.", friend: friend!, minutesAgo: 1, context: context)
    do {
    try context.save()

    }
     catch let error as NSError {
        print("Error \(error.localizedDescription)")
    }

}

但是当我执行相同的步骤时,除了传递两条消息之外,它会抛出错误:

  

CoreData:错误:严重的应用程序错误。抓住了例外   在核心数据更改处理期间。这通常是一个bug   NSManagedObjectContextObjectsDidChangeNotification的观察者。   无效更新:第0部分中的项目数无效   更新后的现有部分中包含的项目(8)必须是   等于该部分之前包含的项目数   更新(6),加上或减去插入或删除的项目数   该部分(1个插入,0个删除)和加号或减号的数量   移入或移出该部分的物品(0移入,0移出)。   with userInfo(null)

也许有人有任何线索?

我实现了:NSFetchController和委托函数:

lazy var fetchedResultsController: NSFetchedResultsController = { () -> NSFetchedResultsController<Message> in
    let fetchRequest = NSFetchRequest<Message>(entityName: "Message")
    fetchRequest.sortDescriptors = [NSSortDescriptor(key:"date",ascending: true)]
fetchRequest.predicate = NSPredicate(format: "friend.name = %@", (self.friend?.name!)!)
    let delegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.persistentContainer.viewContext
    let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
frc.delegate = self
    return frc
}()


   func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
    if type == .insert {
        collectionView?.insertItems(at: [newIndexPath!])
        collectionView?.scrollToItem(at: newIndexPath!, at: .bottom, animated: true)
    }
}

1 个答案:

答案 0 :(得分:0)

如果要插入(或删除,重新加载)多个单元格,则需要在UICollectionView实例的performBatchUpdates方法中进行插入。您需要在func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)中调用它。

请看这个例子:https://github.com/NoFearJoe/Timmee/blob/master/Timmee/Timmee/Sources/Core%20layer/Database/StorageObservable.swift

或: https://gist.github.com/tempire/debbabb2cccafa90320e