John Durand
John Durand

Reputation: 2024

Xcode Debugger: fatal error: Array index out of range.. why?

I'm getting a fatal error: Array index out of range error when i run my application, but I don't see why. Here is my code:

  var rippleLocations: [MKRippleLocation] = [.TapLocation, .TapLocation, .Center, .Left, .Right, .TapLocation, .TapLocation, .TapLocation]
    var circleColors = [UIColor.clearColor(), UIColor.clearColor(),UIColor.clearColor(),UIColor.clearColor()]

 override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return aSport.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! MKTableViewCell
        cell.textLabel?.text = aSport[indexPath.row].name
        cell.textLabel?.text = aSport[indexPath.row].name
        cell.backgroundColor = UIColor.clearColor()
        cell.textLabel?.font = UIFont(name: "HelveticaNeue-Thin", size: 16)
        cell.textLabel?.textColor = UIColor.whiteColor()
        cell.rippleLocation = rippleLocations[indexPath.row]
        let index = indexPath.row % circleColors.count
        cell.rippleLayerColor = circleColors[index]

        return cell
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        let cell = sender as! MKTableViewCell
        let row = tableView.indexPathForCell(cell)?.row
        let detail = segue.destinationViewController as! SecondTableViewController
        detail.selectedSchool = aSport[row!]
    }

The error is highlighted on the cell.rippleLocation = rippleLocations[indexPath.row] string.. why is this error here?

Upvotes: 2

Views: 1920

Answers (2)

Glorfindel
Glorfindel

Reputation: 22651

The number of rows is equal to aSport.count:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return aSport.count
}

Shouldn't that be

    return rippleLocations.count

? Or are you sure that aSport and rippleLocations always have the same number of elements? If you want to cycle through the ripple locations, replace

cell.rippleLocation = rippleLocations[indexPath.row]

with

cell.rippleLocation = rippleLocations[indexPath.row % rippleLocations.count]

Upvotes: 2

Mihir Mehta
Mihir Mehta

Reputation: 13843

It seems like the size of the rippleLocations arrays is less than aSport ...

So for example at the 10th row it will crash if aSport has 10 objects and rippleLocations has 8 objects only.

becuase in numberofRows method you're returning aSport's count

Upvotes: 1

Related Questions