Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fatal error: Index out of range

I want to show 25 of the songs I have in my library. This is my code:

var allSongsArray: [MPMediaItem] = []
let songsQuery = MPMediaQuery.songsQuery()

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 25 //allSongsArray.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell")
    let items = allSongsArray[indexPath.row]
    cell?.textLabel?.text = items.title
    cell?.detailTextLabel?.text = items.artist
    cell?.imageView?.image = items.artwork?.imageWithSize(imageSize)

    return cell!
}

When I run this, it crashes, because:

fatal error: Index out of range

I tried to change the numberOfRowsInSection to allSongsArray.count, but it ends up with the same error.

like image 941
J.Vongehr Avatar asked Mar 28 '16 10:03

J.Vongehr


People also ask

What does Index was out of range mean?

Generally, list index out of range means means that you are providing an index for which a list element does not exist.


1 Answers

You should return allSongsArray.count and to avoid being returned empty cells use yourTableView.reloadData after you fill your allSongsArray.

like image 79
Manuel Avatar answered Nov 20 '22 00:11

Manuel