2017-06-22 52 views
1

目前,我的MainViewController可以连接到我的蓝牙模块并读取来自它的数据。 现在,我试图从另一个View Controller读取数据。从2个UIViewControllers的BLE设备读取值

我的蓝牙管理器是一个单身,所以它不会被多次实例化。为了阅读和处理适当的ViewController中的数据,我想使用可选的委托。它的正常工作,当我到达receivedMVC(数据:字符串)前往receivedUVC时,但崩溃(数据:字符串)

我收到以下错误:

[BLE_Tests.MainViewController receivedUVCWithData:]: unrecognized selector sent to instance 0x100d0a9d0 2017-06-22 16:25:58.634682-0700 BLE_Tests[9544:2692419] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[BLE_Tests.MainViewController **receivedUVCWithData:]: unrecognized selector sent to instance 0x100d0a9d0'

如果我添加receivedUVC(数据:字符串)到我的MainViewController,它不会崩溃,但不会从正确的ViewController调用receivedUVC。

如何指向正确的选择器?

谢谢。

MainViewController.swift

class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, BluetoothDelegate { 

    @IBOutlet weak var peripheralListTableView: UITableView! 
    @IBOutlet weak var updateButton: UIButton! 

    let bluetoothManager = BluetoothManager.getInstance()  

    override func viewDidLoad() { 
     super.viewDidLoad() 

     peripheralListTableView.delegate = self 
     peripheralListTableView.dataSource = self 

     bluetoothManager.delegate = self 
     bluetoothManager.discover() 

    } 

    func reloadPeripheralList() { 
     peripheralListTableView.reloadData() 
    } 

    func receivedMVC(data: String) { 
     print("Hello? \(data)") 
    } 

    //MARK: - UITableViewDataSource 

} 

UpdateViewController.swift

class UpdateViewController: UIViewController, BluetoothDelegate { 

    let bluetoothManager = BluetoothManager.getInstance() 

    func receivedUVC(data: String) { 
     print("Allo: \(data)") 
    } 
} 

BluetoothManager.swift

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {   
    let stringValue = String(data: characteristic.value!, encoding: String.Encoding.utf8)! 
    print("Received packet: \(stringValue)") 

    delegate?.receivedMVC!(data: stringValue) // Delegate method in MainViewController 
    delegate?.receivedUVC!(data: stringValue) // Delegate method in UpdateViewController 
} 

回答

0

[BLE_Tests.MainViewController **receivedUVCWithData:]

这告诉你MainViewController方法收到了UVCWithData:被调用,但该类没有实现它。并且那是原因为什么它被称为:

delegate?.receivedUVC!(data: stringValue) 

这个调用将检查委托存在,如果是,则发送消息到receivedUVC必须存在(!)。所以,如果你把这个它不会崩溃:

delegate?.receivedUVC?(data: stringValue) 

但后来我问自己,为什么你定义你的协议两种不同的方法?在你的协议中定义一个强制的(不是可选的)方法,在两个UIViewControllers中实现它并在BluetoothManager.swift中调用这个方法。然后最后一组委托获取数据。如果两个ViewController同时存在,则您的BluetoothManager需要一个委托1和一个委托2,并调用两个委托上的方法。

+0

傻逼我!我在我的UpdateViewController的ViewDidLoad中忘记了'bluetoothManager.delegate = self',这就是为什么它从未发现它/崩溃。 是的,我应该使用委托?.receivedUVC?(data:stringValue)' 非常感谢:) – downuts