2017-06-22 59 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