【问题标题】:fatal error: Index out of range致命错误:索引超出范围
【发布时间】:2016-03-28 10:35:08
【问题描述】:

我想展示我库中的 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 而不是文字数字;在查询执行之前,数组将包含 0 个项目。发生异常时您尝试访问的索引是什么?
  • 它肯定会以 25 硬编码为行数而崩溃,因为您的数组被声明为空。我怀疑它会与allSongsArray.count 崩溃,但它不会显示任何东西......
  • 哦,是的,你是对的。它不显示任何东西。如何显示 25 首歌曲? @Grimxn
  • MPMediaItem 对象添加(追加)到allSongsArray 并重新加载表格视图

标签: ios swift uitableview


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    当您第一次创建数组时,它是空的。因此,它会给您带来超出范围的错误。

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

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

    这是一个示例代码:

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

    【讨论】:

    • 我试过了,但是单元格是空的。如何用我的歌曲填充单元格?
    • 首先你需要一个函数来填充歌曲数组。他们需要为您的课程添加刷新能力。在刷新操作中,只需使用 tableView.reloadData() 更新表格
    • 检查上面的代码。请注意,您可以从情节提要中添加刷新功能
    【解决方案3】:

    万一您的应用崩溃了

     let items = allSongsArray[indexPath.row]
    

    当您检查 allSongsArray.count 时,您可以通过确保 [indexPath.row] 不超过您的数组计数来保护它。所以你可以写一个简单的 if 条件为;

    if allSongsArray.count > 0 && indexPath.row < allSongsArray.count {
    
      //Do the needful
    
    }
    

    【讨论】:

      【解决方案4】:

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

      return allsongsarray.count
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-20
        • 2016-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多