fatal error: Index out of range

前端 未结 4 2103
长发绾君心
长发绾君心 2021-02-07 11:33

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 numb         


        
相关标签:
4条回答
  • 2021-02-07 11:42

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

    0 讨论(0)
  • 2021-02-07 11:47

    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()
            }
        }
    
    0 讨论(0)
  • 2021-02-07 12:03

    Please return the actual array count instead of static

    return allsongsarray.count
    
    0 讨论(0)
  • 2021-02-07 12:04

    In case your app crashes in

     let items = allSongsArray[indexPath.row]
    

    as you check if the allSongsArray.count, u can safe guard it by making sure that the [indexPath.row] doesn't exceed your array count. so u can write a simple if condition as;

    if allSongsArray.count > 0 && indexPath.row < allSongsArray.count {
    
      //Do the needful
    
    }
    
    0 讨论(0)
提交回复
热议问题