【问题标题】:Casting View Controller that implements a protocol实现协议的铸造视图控制器
【发布时间】:2016-01-08 10:26:13
【问题描述】:

我在同一个视图控制器中有一个包含 CBCentralManager 和 CBPeripheral 组件的工作应用程序,但现在希望分离逻辑以便我可以有一个单独的连接屏幕。我的计划是在连接页面上创建 CBCentralManager,发现并连接外围设备,转到 Dashboard 页面,然后在那里使用 CBPeripheral。

我的代码(精简)如下:

var globalBTDevice : CBPeripheral! // Only using this as a global variable because I can't get this to pass using prepareForSegue

class ConnectionPageViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CBCentralManagerDelegate {
    var centralManager : CBCentralManager!

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        globalBTDevice = self.allFoundDevices[indexPath.row]
        centralManager.stopScan()

        self.performSegueWithIdentifier("connectedPeripheralSegue", sender: self)
    }


    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if segue.identifier == "connectedPeripheralSegue" {
            let destinationVC = segue.destinationViewController as DashboardViewController! // ERROR here: cannot convert value of type "UIViewController" to type "DashboardViewController!" in coercion.
            globalBTDevice.delegate = destinationVC
        }
        centralManager.connectPeripheral(globalBTDevice, options: nil)
    }
}

class DashboardViewController: UIViewController, CBPeripheralDelegate {
    // All delegate methods implemented here
}

我在带有标识符“connectedPeripheralSegue”的 2 个视图控制器之间设置了一个 segue。

此外,DashboardViewController 实际上是用于 TabBarController 的选项卡 - 不确定这是否会有所不同。

所以我遇到的问题是我无法将目标视图控制器转换为标记为 ERROR 的行上的 DashboardViewController。这似乎是由实现 CBPeripheralDelegate 协议的 VC 引起的,好像我删除了它,然后我可以强制转换(但是这使代码无用,因为我在那个类中需要它)。如果我强制转换为 UIViewController 而不是 DashboardViewController,则在下一行设置委托会失败,并显示“无法分配类型为“UIViewController!”的值以键入“CBPeripheralDelegate?”(这是有道理的)。

我完全不知道如何解决这个问题。有人可以帮忙吗?

谢谢!

【问题讨论】:

    标签: ios swift core-bluetooth


    【解决方案1】:

    您应该使用 as? 运算符进行可选类型转换。下面的代码应该可以工作,

    let destinationVC = segue.destinationViewController as? DashboardViewController

    【讨论】:

    • 谢谢!它现在编译。不幸的是,连接的外围设备似乎永远不会触发 DashboardViewController 中的任何 CBPeripheralDelegate 方法(即使我已将其设置为委托),所以我仍然需要做一些工作来查看问题所在。我开始认为您只需要将 CBPeripheralDelegate 与 CBCentralManagerDelegate 放在同一个类中。如果我解决了我的问题,无论如何我都会在这里发帖。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多