ios ble 在 Swift fatal error : Index out of range 中使用 tableview 连接多个设备

标签 ios swift bluetooth-lowenergy

我想展示关于未连接和已连接的两个部分 我的 swift 不是很好。

这是我的代码 https://www.codepile.net/pile/vNYKLZ6L

当我运行它时,它会在这里崩溃 let peripheral = self.peripherals[indexPath.row]

fatal error: Index out of range

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //Connect to device where the peripheral is connected
    let cell = tableView.dequeueReusableCell(withIdentifier: "BlueCell") as! PeripheralTableViewCell
    let peripheral = self.peripherals[indexPath.row]
    //let RSSI = self.RSSIs[indexPath.row]

    if indexPath.section == 0 {
        if peripheral.name == nil {
           cell.peripheralLabel?.text = "nil"
        } else {
           cell.peripheralLabel?.text = peripheral.name
        }
    } else {
       if connectPeripherals.count == 0 {
          cell.peripheralLabel?.text = "nil"
       } else {            
          cell.peripheralLabel?.text = self.connectPeripherals[indexPath.row].name
       }
    }

    //cell.rssiLabel.text = "RSSI: \(RSSI)"
    print("tableview連線有\(connectPeripherals.count)個")
    print("tableview未連線有\(peripherals.count)個")

    return cell
}

这里是 numberOfRowsInSection 函数

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0{
        return self.peripherals.count
    } else {
        return self.connectPeripherals.count
    }
}

最佳答案

据我所知,peripherals 在 section_0 上,connect Peripherals 在 section_1 上,因此您可以这样重新组织代码:

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

    if indexPath.section == 0 {
        let peripheral = self.peripherals[indexPath.row]
        cell.peripheralLabel?.text = peripheral.name != nil ? peripheral.name : "nil"
    } else {
        let connectedPeripheral = self.connectPeripherals[indexPath.row]
        cell.peripheralLabel?.text = connectedPeripheral.name != nil ? connectedPeripheral.name : "nil"
    }

    print("tableview連線有\(connectPeripherals.count)個")
    print("tableview未連線有\(peripherals.count)個")
    return cell
}

关于ios ble 在 Swift fatal error : Index out of range 中使用 tableview 连接多个设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48364626/

相关文章:

swift - NSWindow 宽度未使用 setFrame(frame, display, animate) 更新

python - 树莓派蓝牙 - 发送数据

android - 用于蓝牙通信的 GATT over SPP 配置文件?

ios - 如何在核心数据发生变化时预览数据库?

ios - 限制 gameScene 的边

swift - 弹出窗口有黑色背景,即使它设置为清除

ios - swift3 中的数据到 Int/String

ios - AF 网络 2.0 : is it possible to put pure json in the body of a POST request?

ios - 如何在 Objective C 中的日历上添加来自 Web 服务的事件

swift - 从自定义 .plist 文件中读取用户定义的设置