[英]fatal error: Index out of range
我想展示我库中的 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!
}
当我运行它时,它崩溃了,因为:
致命错误:索引超出范围
我试图将numberOfRowsInSection
更改为allSongsArray.count
,但最终出现相同的错误。
您应该返回allSongsArray.count
,避免返回空单元格使用yourTableView.reloadData
你填写你以后allSongsArray
。
当您第一次创建数组时,它是空的。 因此,它会给你越界错误。
尝试返回歌曲数组的计数。
首先,您需要将数据放入数组中,然后更新表视图。
这是一个示例代码:
@IBAction private func refresh(sender: UIRefreshControl?) {
if myArray.count > 0 {
self.tableView.reloadData()
sender?.endRefreshing()
} else {
sender?.endRefreshing()
}
}
如果您的应用程序崩溃
let items = allSongsArray[indexPath.row]
当您检查 allSongsArray.count 时,您可以通过确保 [indexPath.row] 不超过您的数组计数来保护它。 所以你可以写一个简单的 if 条件;
if allSongsArray.count > 0 && indexPath.row < allSongsArray.count {
//Do the needful
}
请返回实际数组计数而不是静态
return allsongsarray.count
对于寻找在过滤列表上滑动的解决方案的人,您需要提供该部分以及行,否则 xcode 会引发此错误。
func swipe(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let myRow = filteredList[indexPath.section].items[indexPath.row]
}
不是
func swipe(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let myRow = filteredList[indexPath.row]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.