【问题标题】:Index out of range for cell text单元格文本的索引超出范围
【发布时间】:2025-12-22 19:15:07
【问题描述】:

我正在制作一个购物应用,但遇到了问题。

到目前为止,我一直在解析 json,制作了一个 tableview 单元格,但我遇到了一个错误,它说超出范围:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "hello", for: indexPath) as! DisplayShopTableCellTableViewCell

    // Configure the cell...

    cell.userLbl.text = namee[indexPath.row]  //Index out of range
    cell.passLbl.text = myprice[indexPath.row]
    
    let imagedata = try! Data(contentsOf: mySecond[indexPath.row].imageUrl!)
    cell.tablecellimageview.image = UIImage(data: imagedata)
    
    return cell
}

这是我的展示店表格单元格:

class DisplayShopTableCellTableViewCell: UITableViewCell {
    
    @IBOutlet weak var userLbl: UILabel!
    @IBOutlet weak var passLbl: UILabel!
    @IBOutlet weak var tablecellimageview: UIImageView!

解析

func extracted(){
    guard let url = URL(string: "http://rajeshrmohan.com/sport.json")
    else {
        return
    }
    
    let task = URLSession.shared.dataTask(with: url){
        (data,response,error) in
        guard let dataResponse = data,
              error == nil else {
            print(error?.localizedDescription ?? "Response Error")
            return
        }
        
        do {
            let decoder = JSONDecoder()
            let model = try decoder.decode(FullClothes.self, from: dataResponse)
            //print(model)
            
            for i in 0..<model.item.count{
                self.namee.append(model.item[i].name!)
                self.myprice.append(String(model.item[i].price!))
                self.myphoto.append(model.item[i].image!)
            }
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
        catch let parsingError {
            print("Error", parsingError)
        }
    }
    task.resume()
}

【问题讨论】:

  • cellForRowAt 委托方法下编写的代码不太合理。为什么要使用两个单独的数组来制作单元格?
  • 存储数据并用于上面的解析没有?

标签: arrays json swift parsing


【解决方案1】:

我认为解析是以错误的方式完成的,另外,正如 El Tomato 评论的那样,为什么使用多个数组来构造一个单元格,再添加一个评论,配置单元格不应该在 cellForRowAt 内完成,最好在里面完成细胞本身。 检查以下代码 sn-p 如果您需要任何帮助,请告诉我。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "hello", for: indexPath) as! DisplayShopTableCellTableViewCell

    // Configure the cell...
    cell.bind(self.myData[indexPath.row])
    return cell
}

class DisplayShopTableCellTableViewCell: UITableViewCell {
    @IBOutlet weak var userLbl: UILabel!
    @IBOutlet weak var passLbl: UILabel!
    @IBOutlet weak var tablecellimageview: UIImageView!
    func bind(_ cellData: Item) {
        self.userLbl.text = cellData.name
        self.passLbl.text = String(cellData.price)
        guard let imageURL = URL(string: "\(cellData.image)") else {
            preconditionFailure("Invalid static URL string: \(cellData.image)")
        }
        guard let imagedata = try? Data(contentsOf: imageURL) else {
            return
        }
        self.tablecellimageview.image = UIImage(data: imagedata)
    }
}

struct Item: Decodable {
    let name: String
    let price: Float
    let image: String
}

func extracted() {
    guard let url = URL(string: "http://rajeshrmohan.com/sport.json")
    else {
        return
    }
    
    let task = URLSession.shared.dataTask(with: url){
        (data,response,error) in
        guard let dataResponse = data,
              error == nil else {
            print(error?.localizedDescription ?? "Response Error")
            return
        }
        
        do {
            let decoder = JSONDecoder()
            let items: [Item] = try decoder.decode([Item].self, from: dataResponse)
            //print(model)
            
            for i in 0..<items.count {
                self.myData.append(items[i])
            }
        }
        catch let parsingError {
            print("Error", parsingError)
        }
    }
    task.resume()
}

最后,尽量避免强制转换,请查看this question 了解有关强制转换的更多信息。

Optional chaining 也会有所帮助。

【讨论】: