Lawrence413 Lawrence413 - 11 months ago 138
Swift Question

UITableView.insertRowsAtIndexPaths not working

I'm using Core Data and I have a problem. The app crashes because when I insert a new element I try to access a cell that doesn't exist but it should.

The code that matters:

func controllerWillChangeContent(controller: NSFetchedResultsController) {

func controllerDidChangeContent(controller: NSFetchedResultsController) {

func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
if let indexPath = newIndexPath {
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) // This doesn't work
print(indexPath) // Returns row 0 section 0
print(tableView.numberOfRowsInSection(0)) // Returns 0
print(tableView.cellForRowAtIndexPath(indexPath)) // Returns nil

let cell = tableView.cellForRowAtIndexPath(indexPath) as! myCell // App crashes here because cell is nil
configureCell(cell, atIndexPath: indexPath)

self.tableView.backgroundView = nil

Crash Log:

<UITableView: 0x7ffb1b8c3000; frame = (0 64; 375 554); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x7ffb1ae9a620>; layer = <CALayer: 0x7ffb1ae92b40>; contentOffset: {0, 0}; contentSize: {375, 10}>
<NSIndexPath: 0xc000000000000016> {length = 2, path = 0 - 0}
fatal error: unexpectedly found nil while unwrapping an Optional value

Sorry for putting the log as code but there's a bug with the block quote and won't show the full log.

This is very weird because it was working fine before. I just did some changes to the code (code snippet includes changes) but didn't touch the
and now it's not working.

Answer Source

It's normal ! Indeed, cellForRowAtIndexPath on UITableView "returns an object representing a cell of the table, or nil if the cell is not visible or indexPath is out of range". (Source).

So, you can't access this cell because it do not exists yet for the UITableView (you are adding it !). Please, move your configureCell call to your datasource tableView(_:cellForRowAt:).