title: How to prevent NSInternalInconsistencyException with Realm and UICollectionView
body: <p>I have a UICollectionView that is populated from Realm. Some users, seemingly at random, get a NSInternalInconsistencyException stating something like</p>
  
  <blockquote>
    <p>Invalid update: invalid number of items in section 0. The number of
    items contained in an existing section after the update (73) must be
    equal to the number of items contained in that section before the
    update (73), plus or minus the number of items inserted or deleted
    from that section (1 inserted, 0 deleted) and plus or minus the number
    of items moved into or out of that section (0 moved in, 0 moved out).</p>
  </blockquote>
  
  <p>My code is based on Realm's collection example. It selects and filters some records:</p>
  
  <p><code>self.assets = realm.objects(Asset.self).filter("is_deleted = false")</code></p>
  
  <p>And then it subscribes to and handles notifications:</p>
  
  <pre><code>self.assetsNotificationToken = self.assets!.addNotificationBlock(){ [weak self] (changes: RealmCollectionChange) in
  
      guard let collectionView = self!.collectionView else { return }
  
      guard let strongSelf = self else { return }
  
      switch changes {
  
          case .Initial:
  
              collectionView.reloadData()
  
          case .Update(let _, let deletions, let insertions, let modifications):
  
              strongSelf.collectionView?.performBatchUpdates({
  
                  collectionView.insertItemsAtIndexPaths(insertions.map { NSIndexPath(forRow: $0, inSection: 0) })
  
                  collectionView.reloadItemsAtIndexPaths(modifications.map { NSIndexPath(forRow: $0, inSection: 0) })
  
                  collectionView.deleteItemsAtIndexPaths(deletions.map { NSIndexPath(forRow: $0, inSection: 0) })
  
              }, completion: nil)
  
          case .Error(let error):
  
              log.error(error.localizedDescription)
              break
  
      }
  
  }
  </code></pre>
  
  <p>The count comes from:</p>
  
  <pre><code>override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {
  
      guard assets != nil else {
          return 0;
      }
  
      return assets!.count
  
  }
  </code></pre>
  
  <p><strong>I later switched to <a href="https://github.com/bigfish24/ABFRealmGridController/" rel="nofollow">RealmGridController</a></strong></p>
  
  <p>Unable to find the source of the crash, I switched to <a href="https://github.com/bigfish24/ABFRealmGridController/" rel="nofollow">RealmGridController</a>. It's a package written by a Realm core contributor and it encapsulates all of the standard functionality needed for working with realm + CollectionViews. </p>
  
  <p>It seemed to work, and then I started seeing the exact same crash. </p>
  
  <blockquote>
    <p>Fatal Exception: NSInternalInconsistencyException Invalid update:
    invalid number of items in section 0. The number of items contained in
    an existing section after the update (78) must be equal to the number
    of items contained in that section before the update (78), plus or
    minus the number of items inserted or deleted from that section (2
    inserted, 0 deleted) and plus or minus the number of items moved into
    or out of that section (0 moved in, 0 moved out).</p>
  </blockquote>
  
  <pre><code>Fatal Exception: NSInternalInconsistencyException
  0  CoreFoundation                 0x1839dadb0 __exceptionPreprocess
  1  libobjc.A.dylib                0x18303ff80 objc_exception_throw
  2  CoreFoundation                 0x1839dac80 +[NSException raise:format:]
  3  Foundation                     0x184360154 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:]
  4  UIKit                          0x18938b00c -[UICollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:]
  5  UIKit                          0x18938e464 -[UICollectionView _performBatchUpdates:completion:invalidationContext:tentativelyForReordering:]
  6  UIKit                          0x18938e2e0 -[UICollectionView _performBatchUpdates:completion:invalidationContext:]
  7  UIKit                          0x188d2c2a4 -[UICollectionView performBatchUpdates:completion:]
  8  RealmGridController            0x1014a8340 specialized RealmGridController.controllerDidChangeContent(RBQFetchedResultsController) -&gt; () (RealmGridController.swift:316)
  9  RealmGridController            0x1014a687c @objc RealmGridController.controllerDidChangeContent(RBQFetchedResultsController) -&gt; () (RealmGridController.swift)
  10 RBQFetchedResultsController    0x100ff8edc __112-[RBQFetchedResultsController calculateChangesWithAddedSafeObjects:deletedSafeObjects:changedSafeObjects:realm:]_block_invoke.433 (RBQFetchedResultsController.m:842)
  11 libdispatch.dylib              0x1834254bc _dispatch_call_block_and_release
  </code></pre>