You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中iOS BLE多设备连接TableView崩溃:数组越界问题求助

解决TableView分区展示蓝牙设备时的数组越界崩溃问题

嘿,我看了你遇到的问题——在cellForRowAt方法里触发了数组越界的致命错误,这其实是个很典型的数据源匹配失误,咱们一步步来搞定它:

问题根源

你现在的代码不管当前是哪个分区,都会先执行let peripheral = self.peripherals[indexPath.row],但当分区是1(已连接设备分区)时,indexPath.row对应的是connectPeripherals的索引,而非peripherals的。如果这两个数组的元素数量不一致,必然会触发数组越界的崩溃。

修复方案

我们需要严格根据当前分区选择对应的数据源,而不是先统一取peripherals的数据。修改后的cellForRowAt方法如下:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "BlueCell") as! PeripheralTableViewCell
    
    // 按分区匹配对应数据源
    if indexPath.section == 0 {
        // 未连接分区:使用peripherals数组
        let peripheral = self.peripherals[indexPath.row]
        cell.peripheralLabel?.text = peripheral.name ?? "未知设备"
    } else {
        // 已连接分区:使用connectPeripherals数组
        let connectedPeripheral = self.connectPeripherals[indexPath.row]
        cell.peripheralLabel?.text = connectedPeripheral.name ?? "未知已连接设备"
    }
    
    print("tableview已连接有\(connectPeripherals.count)个")
    print("tableview未连接有\(peripherals.count)个")
    return cell
}

额外优化建议

  • 我把原来的nil替换成了更友好的提示文本,用户体验会更顺畅;
  • 务必记得:在更新peripherals或connectPeripherals数组后,调用tableView.reloadData()刷新界面,避免数据源和界面状态不同步;
  • 如果担心数组为空的场景,你当前的numberOfRowsInSection逻辑是正确的——数组为空时返回0,不会走到cellForRowAt方法,所以无需额外处理空数组的行渲染问题。

这样修改后,每个分区都会精准匹配自己的数据源,数组越界的问题就彻底解决啦。

内容的提问来源于stack exchange,提问作者leehao178

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:37:22