当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - fatal error: Index out of range

问题描述:

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 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 "Index out of range". I tried to change the numberOfRowsInSection to allSongsArray.count, but it ends up with the same error.

网友答案:

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

网友答案:

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()
        }
    }
网友答案:

Please return the actual array count instead of static

return allsongsarray.count
分享给朋友:
您可能感兴趣的文章:
随机阅读: