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。目標是等待異步函數/委託從同步執行而不凍結。
有關如何弄清楚的任何想法?
不要試圖等待。處理它是異步的事實。使用委託,回調關閉或NSNotification – Paulw11
在代理中使用委託並不是一種更簡潔的方式。完成處理程序被同步調用。可能NSNotification可能是問題解決者 – lucio
我的選擇可能是一個完成處理程序,但NSNotification也可以工作 – Paulw11