我正在尝试使用Promisekit实现带有包裹委派的Singleton
我设法按照此处的描述实现: https://github.com/mxcl/PromiseKit/issues/136
它有效,但承诺保留了第一次通话的价值。它没有更新价值。
示例代码:
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: "")
}
}
答案 0 :(得分:1)
Promise只能实现一次,因此仅适用于满足一次的系统。对于像套接字这样的东西,你应该使用另一种异步模式,比如完成块。