gpt4 book ai didi

ios - 返回值之前等待委托(delegate)执行

转载 作者:行者123 更新时间:2023-11-30 13:41:55 25 4
gpt4 key购买 nike

我有一些带有 getter 和 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。目标是等待同步函数/委托(delegate)执行而不卡住。

知道如何解决这个问题吗?

最佳答案

一种可能的方法是不将名称作为属性访问,而是编写一个方法调用来请求名称并期望委托(delegate)调用相同的名称,并在此委托(delegate)调用中执行您需要的任何操作。

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)
}
}

关于ios - 返回值之前等待委托(delegate)执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35467076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com