title: Preventing crash in UICollectionView
body: <p>Our app has <code>UICollectionView</code> and its <code>dataSource</code> dictionary is regularly updated. We never know when next update will happen. Collection View reload method could be called after user taps a button or it could happen asynchronous after network request success. Given above information we have the risk to have a race condition while reloading collection view and updating its data source at the same time. We even registered the following crash and we believe its happened because of the race condition described above. The crash message:</p>
  
  <pre><code>*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
  </code></pre>
  
  <p>The method which cause the crash: <code>collectionViewLayout sizeForItemAtIndexPath:</code>.</p>
  
  <p>This method calculates height for collection View's section depending on items count in the <code>sectionWithProducts</code>. It crashes because <code>dataSource</code> count is smaller than <code>indexPath.row</code>. And the line causing the crash:</p>
  
  <p><code>NSArray *sectionWithProducts = self.dataSource[indexPath.row];</code></p>
  
  <p>Following lines called before crash happened:</p>
  
  <pre><code>[self.collectionView setCollectionViewLayout:[self flowLayout] animated:NO];
  [self.collectionView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
  [self.collectionView reloadData];
  </code></pre>
  
  <p>To prevent this we decided to put the only line of code which updates data source into main thread.</p>
  
  <pre><code>// Always run on main thread in hope to prevent NSRangeException. 
  // Reloading data should happen only sequential.
  dispatch_async(dispatch_get_main_queue(), ^(void) {
      self.dataSource = newValue;
  });
  </code></pre>
  
  <p>We had lots of <code>[self.collectionView reloadData]</code> in our code. Is it worth to run them on main thread as well? It happened quickly so it shouldn't block UI for long. </p>
  
  <p>Is <code>UICollectionViewDelegateFlowLayout</code> delegate methods with <code>indexPath</code> property always called on background queue?</p>