Ios 在返回值之前等待委托执行
我有一些带有getter和setter的类属性,它们向设备发送一些命令来设置或获取一些值。CoreBluetooth异步工作,因此,对于ie,在返回值之前,我必须检查设备是否响应了命令,检查响应有效性,然后将值返回给调用者 只是想弄清楚Ios 在返回值之前等待委托执行,ios,swift,Ios,Swift,我有一些带有getter和setter的类属性,它们向设备发送一些命令来设置或获取一些值。CoreBluetooth异步工作,因此,对于ie,在返回值之前,我必须检查设备是否响应了命令,检查响应有效性,然后将值返回给调用者 只是想弄清楚 class A: Delegate { func peripheral( peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic:
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。目标是等待同步函数/委托执行而不冻结
有没有办法解决这个问题?一种可能的方法不是将name作为属性访问,而是编写一个方法调用来请求name,并期望对name进行委托调用,在这个委托调用中,您可以执行任何需要的操作
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)
}
}
不要试图等待。处理它是异步的这一事实。使用委托、回调闭包或NSNotification在委托中使用委托似乎不是一种更干净的方法。完成处理程序被同步调用。NSNotification可能是问题的解决方案。我可能会选择一个完成处理程序,但NSNotification可能工作得太好,您不能真正使用属性getter,因为您的底层数据源是异步的。这取决于值是否可以通过Bkuetooth通知异步更新,以及是否有多个观察者希望同时了解值更改。在这些情况下,您将使用NSNotification。如果只有一个观察者需要该值,并且他们必须从设备请求该值,那么您可以将完成处理程序存储在由特征键控的字典中,发出读取,然后在读取完成时调用存储的完成处理程序。如果可能,完成处理程序将是一个完美的解决方案,但是,假设这段代码,您会注意到完成处理程序无法解决问题