首页 > 解决方案 > UICollectionView 使用领域通知执行批量更新崩溃

问题描述

我正在为我的消息传递应用程序使用领域 Swift。我用于消息传递的基本视图是自定义 UICollectionView,我使用领域 swift 进行数据存储。不幸的是,我在领域中找不到任何官方示例,用于使用领域通知更新集合视图。因此,当我通过为该领域列表添加观察者从领域获取通知令牌时,我实现了这样的实现,因此当来自该通知的更新时,我执行批量更新并删除、插入和修改领域告诉我在此通知中执行的索引。我的应用程序在测试环境中运行良好,但在生产中我遇到了一些崩溃,这些崩溃报告了我的面料,告诉我应用程序崩溃,这是由批量更新引起的。他们的信息大多像

invalid update: invalid number of sections. The number of sections contained in the collection view after the update (1) must be equal to the number of sections contained in the collection view before the update (1), plus or minus the number of sections inserted or deleted (0 inserted, 1 deleted).  

或更新后部分中的项目数无效等。我现在很困惑。有任何想法吗?

我执行此更新的代码

notificationToken = dbmsgs?.observe { [weak self] (changes: RealmCollectionChange) in
  switch changes{
  case .initial:
    print("intial")
    self?.collectionView.reloadData()
  case .update(_,let deletions,let insertions,let modifications):
    self?.collectionView.performBatchUpdates({
      if deletions.count > 0{
        print("deletions count\(deletions.count)")
        if (self?.collectionView.numberOfItems(inSection: 0) ?? 0) - deletions.count > 0 {
          self?.collectionView.deleteItems(at: deletions.map { IndexPath(row: $0, section: 0) })
        }
        else{
          self?.collectionView.deleteSections(IndexSet(integer: 0))
        }
      }
      if insertions.count > 0{
        print("insertaions count\(insertions.count)")
        for index in insertions{
          guard let lastdbmsg = self?.dbmsgs?[index] else{
            return
          }
          let sectionIndex = 0
          let itemIndex = ( self?.dbmsgs != nil) ? (self?.dbmsgs?.count)! - 1 : 0
          if itemIndex == 0{
            self?.collectionView.insertSections([0])
          }
          self?.collectionView.insertItems(at: [IndexPath(item: itemIndex, section: sectionIndex)])
          if itemIndex != 0{
            self?.collectionView.reloadItems(at: [IndexPath(row: itemIndex-1, section: 0)])
          }

        }
      }
      if modifications.count > 0{
        self?.collectionView.reloadItems(at: modifications.map({ IndexPath(row: $0, section: 0)}))
      }
    },completion: { (_) in
    })
  case .error(let error):
    // An error occurred while opening the Realm file on the background worker thread
    fatalError("\(error)")
  }
}

标签: iosswiftuicollectionviewrealmperformbatchupdates

解决方案


推荐阅读