0

I know that there have been a lot of questions asked on this error but I went through all of them and none of them helped. I'm calling the function addCell() from my main class and the code below is what I have in my TableViewControllerClass. I definitely have my requestIdentifier "cell" linked up in my .storyboard, and the arrays "locations" and "times" are definitely not empty because I print them when the error occurs, so the problem has to be with my "table" variable, that is also properly linked to the table view, but is evidently nil for some reason. Any suggestions?

func addCell(){

    //update to insertion sort

    currLocation = addLocation

    if (locations == [""] && times == [0]) {

        self.locations.removeAll()

        self.times.removeAll()

    }

    if !(locations.isEmpty){

        if locations[locations.count-1] != currLocation {

            var count = 0

            var neverVisited = true

            for location in locations{

                if location == currLocation{

                    neverVisited = false

                    times[count] += addTime

                    count++

                }

            }

            if neverVisited {

                locations.append(currLocation)

                times.append(addTime)

            }

        } else {

            times[times.count-1] = addTime

        }

    } else {

        locations.append(currLocation)

        times.append(addTime)

    }

    print(locations) //not empty
    print(times) //not empty

    table.reloadData() //crashes here

}




override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

    cell.textLabel?.text = locations[indexPath.row] + ", \(times[indexPath.row])"

    }

    return cell

}
  • "properly linked to the table view" does not mean your `table` can never be `nil`. Aren't you calling `addCell()` before `table` is given an actual content? – OOPer Aug 02 '16 at 23:09
  • Possible duplicate of [Fatal error: unexpectedly found nil while unwrapping an Optional values](http://stackoverflow.com/questions/24643522/fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-values) – gnasher729 Aug 02 '16 at 23:42

1 Answers1

0

You can solve the issue with a guard statement at the end or beginning (depending if you want to perform all the logic even if the table is not yet present) of your addCell() function before the call of reloadData function :

guard let tmpTable = table else {
        return
    }

You could also use :

if let tmpTable = table else {
        tmpTable.reloadData()
    }

That way the function that cause the issue will be call only if your table is already loaded. Also it's a bit weird to use your main class, usually this class is not used to perform any code/logic, try to use the right controller instead.

RomOne
  • 1,905
  • 13
  • 27