在返回值之前等待委托执行

时间:2016-02-17 20:29:45

标签: ios swift

我有一些带有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 对象等待条件变为true但可能会冻结UI。目标是等待同步函数/委托执行而不冻结。

关于如何弄明白的想法?

1 个答案:

答案 0 :(得分:0)

一种可能的方法是不要将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)
     }
}