ios 致命错误:索引超出范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36260542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
fatal error: Index out of range
提问by J.Vongehr
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
,但最终出现相同的错误。
回答by Manuel
You should return allSongsArray.count
and to avoid being returned empty cells use yourTableView.reloadData
after you fill your allSongsArray
.
您应该返回allSongsArray.count
并避免返回空单元格yourTableView.reloadData
在您填写allSongsArray
.
回答by Ali Alebrahim
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()
}
}
回答by Sabby
Please return the actual array count instead of static
请返回实际数组计数而不是静态
return allsongsarray.count