2016-02-17 57 views
0

我有一些具有getters和setter的類屬性,它們向設備發送一些命令來設置或獲取某些值。 CoreBluetooth異步工作,因此,例如,在返回值之前,我必須檢查設備是否響應了命令,檢查響應有效性,然後將該值返回給調用者。在返回值之前等待委託執行

正好有一個清晰的思路...

class A: Delegate { 
    func peripheral(
     peripheral: CBPeripheral, 
     didUpdateValueForCharacteristic characteristic: CBCharacteristic, 
     error: NSError?) 
    { 
     // receive some data, parse it and assign to lastResponse 
     A.lastResponse = ... 
    } 

} 

class A { 
    static var lastResponse: SomeObject? 

    // get or set device name 
    static var name: String { 
     get { 
      // send command to device 
      ... 

      // wait until a response is received 
      ... 

      return lastResponse.value 
     } 
     set { 
      // same as getter but have to ensure that the command 
      // has been received from device by checking the response code 
     } 
    } 
} 

我的想法是使用NSCondition目標要等到條件爲真,但可能它會凍結UI。目標是等待異步函數/委託從同步執行而不凍結。

有關如何弄清楚的任何想法?

+5

不要試圖等待。處理它是異步的事實。使用委託,回調關閉或NSNotification – Paulw11

+0

在代理中使用委託並不是一種更簡潔的方式。完成處理程序被同步調用。可能NSNotification可能是問題解決者 – lucio

+0

我的選擇可能是一個完成處理程序,但NSNotification也可以工作 – Paulw11

回答

0

一種可能的方式是不要訪問名稱作爲屬性,而是編寫一個方法調用來請求名稱,並期待相同的代理調用,並在此代理調用中執行您需要的任何操作。

class protocol Delegate { 
    func deviceName(name: String); 
} 

class A: Delegate { 
     func peripheral(
      peripheral: CBPeripheral, 
      didUpdateValueForCharacteristic characteristic: CBCharacteristic, 
      error: NSError?) 
     { 
      // receive some data, parse it and assign to lastResponse 
      A.lastResponse = ... 
      A.delegate = self 
      A.requestName() 
     } 

     func deviceName(name: String) { 
      //do what u wish with the name 
     } 

    } 

    class A { 
     static var lastResponse: SomeObject? 
     var delegate: Delegate? 

     // get or set device name 
     static var name: String? 


    func requestName() { 
     ... 
     // send command to device 
     ... 

     // when a response is received 
     ... 
     name = //name received 
     delegate.deviceName(name) 
    } 
}