致命错误:索引超出范围

时间:2021-01-02 16:38:38

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

我想在我的图书馆中播放25首歌曲。这是我的代码:

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.

我试图将numberOfRowsInSection更改为allSongsArray.count,但最终会出现相同的错误。

3 个解决方案

#1


12  

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

您应该返回allSongsArray.count并避免返回空单元格在填充allSongsArray后使用yourTableView.reloadData。

#2


2  

When you first create the array it is empty. Hence, it will give you out of bound error.

第一次创建数组时,它是空的。因此,它会给你出界的错误。

Try to return the count of the songs array instead.

尝试返回歌曲数组的计数。

1st you need to get the data into the array and then update the table view.

首先,您需要将数据放入数组,然后更新表视图。

Here is a sample code:

这是一个示例代码:

@IBAction private func refresh(sender: UIRefreshControl?) {
        if myArray.count > 0 {
              self.tableView.reloadData()
              sender?.endRefreshing()
        } else {
              sender?.endRefreshing()
        }
    }

#3


0  

Please return the actual array count instead of static

请返回实际的数组计数而不是静态数

return allsongsarray.count

#1


12  

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

您应该返回allSongsArray.count并避免返回空单元格在填充allSongsArray后使用yourTableView.reloadData。

#2


2  

When you first create the array it is empty. Hence, it will give you out of bound error.

第一次创建数组时,它是空的。因此,它会给你出界的错误。

Try to return the count of the songs array instead.

尝试返回歌曲数组的计数。

1st you need to get the data into the array and then update the table view.

首先,您需要将数据放入数组,然后更新表视图。

Here is a sample code:

这是一个示例代码:

@IBAction private func refresh(sender: UIRefreshControl?) {
        if myArray.count > 0 {
              self.tableView.reloadData()
              sender?.endRefreshing()
        } else {
              sender?.endRefreshing()
        }
    }

#3


0  

Please return the actual array count instead of static

请返回实际的数组计数而不是静态数

return allsongsarray.count