title: UICollectionViewFlowLayout subclass crashes accessing array beyond bounds while scrolling and reloading
body: <p>I have a UICollectionView that uses a custom subclass of UICollectionViewFlowLayout to make the section headers stick to the top of the screen while scrolling just like UITableView's plain style. My code is based on this approach:</p>
  
  <p><a href="http://blog.radi.ws/post/32905838158/sticky-headers-for-uicollectionview-using" rel="noreferrer">http://blog.radi.ws/post/32905838158/sticky-headers-for-uicollectionview-using</a></p>
  
  <p>In addition, the collection view is set up to load more results when the user scrolls to the bottom. That is, when the user gets to the bottom of the collection view, a web request loads more data and then reloads the collection view, i.e. calling reloadData.</p>
  
  <p>It seems to work well except I've been getting a few crash reports from beta testers via TestFlight running iOS 7 and 7.1 who say that the following happens occasionally when they scroll down to the bottom (i.e. triggering more results to load) quickly:</p>
  
  <pre><code>*** -[__NSArrayM objectAtIndex:]: index 28 beyond bounds [0 .. 16]
  PRIMARY THREAD THREAD 0
  
  __exceptionPreprocess
  objc_exception_throw
  -[__NSArrayM objectAtIndex:]
  -[UICollectionViewFlowLayout(Internal) _frameForItemAtSection:andRow:usingData:]
  -[UICollectionViewFlowLayout layoutAttributesForItemAtIndexPath:usingData:]
  -[UICollectionViewFlowLayout layoutAttributesForItemAtIndexPath:]
  -[MyCustomCollectionViewFlowLayout layoutAttributesForItemAtIndexPath:]
  -[MyCustomCollectionViewFlowLayout layoutAttributesForSupplementaryViewOfKind:atIndexPath:]
  -[MyCustomCollectionViewFlowLayout layoutAttributesForElementsInRect:]
  -[UICollectionViewData validateLayoutInRect:]_block_invoke
  -[UICollectionViewData validateLayoutInRect:]
  -[UICollectionView layoutSubviews]
  -[UIView(CALayerDelegate) layoutSublayersOfLayer:]
  -[CALayer layoutSublayers]
  </code></pre>
  
  <p>It seems as though when my custom flow layout code calls <code>[self.collectionView numberOfItemsInSection:someSection]</code> to get the layout attributes of a section's last item, that call returns based on the newly-loaded data (e.g. in this case that a section now has 29 items) but the internals of the default flow layout are still using some kind of cached data (e.g. in this case that the section only has 17 items). Unfortunately, I can't reproduce the crash myself and even the beta testers who have experienced it can't reproduce it consistently. </p>
  
  <p>Any ideas what's going on there?</p>