gpt4 book ai didi

ios - PromiseKit 4 - 包装委托(delegate)

转载 作者:行者123 更新时间:2023-11-28 06:32:21 24 4
gpt4 key购买 nike

我正在尝试使用 Promisekit 通过 Wrap Delegation 实现单例

我设法按照此处所述实现了这一点: https://github.com/mxcl/PromiseKit/issues/136

它有效,但 promise 会保留第一次调用的值。它不更新值。

示例代码:

open class APIClient: NSObject {


static let sharedInstance = APIClient()
var mSocket: GCDAsyncSocket!
var deferred = Promise<[String:Any]>.pending()
var retainCycle: NSObject?

override init() {
mSocket = GCDAsyncSocket()
super.init()
mSocket.setDelegate(self, delegateQueue: DispatchQueue.main)
deferred.promise.always {
print(self) // here we force a retain on self inside the promise object
// it will be released once processed
}.catch { (error) in

}
}


// MARK: - sendMessageTCP
open func sendMessageTCP(message data:Data) -> Promise<[String:Any]> {
mSocket.write(data, withTimeout: 10, tag: 0)
return deferred.promise
}

}

extension APIClient: GCDAsyncSocketDelegate {

public func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) {
sock.readData(withTimeout: -1, tag: 0)
}

public func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
let array = data.withUnsafeBytes {
[UInt8](UnsafeBufferPointer(start: $0, count: data.count))
}
let parameters: [String:Any] = [
"status": true,
"data": bytesToHexString(bytes: array),
"ui_message": "Read Data"
]
deferred.fulfill(parameters)
retainCycle = nil
}

private func bytesToHexString(bytes: [UInt8]) -> String {
return bytes.map{String(format: "%02X", $0)}.joined(separator: "")
}

}

最佳答案

Promises 只能实现一次,因此只适用于实现一次的系统。对于套接字之类的东西,您应该使用另一种异步模式,例如完成 block 。

关于ios - PromiseKit 4 - 包装委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39968966/

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