NSStreams 代码仅在调试器模式下按预期工作

NSStreams-code works as expected just in the debugger mode

一切都按预期工作,只是逐步抛出调试器,否则我会得到 EXC_BAD_ACCESS。我想我需要在某个地方延迟或等待(最好)某事。

// 1) Create streams(input/output)
Stream.getStreamsToHost(withName: _host, port: _port, inputStream: &self._input_stream, outputStream: &self._output_stream);
if (self._input_stream == nil || self._output_stream == nil) {
    self._promise.reject(HTTPSocketStreamError());
    return self._promise;
}
// 2) Delegate to self
self._input_stream!.delegate = self;
self._output_stream!.delegate = self;

// 3) Set dispatch queues
CFReadStreamSetDispatchQueue(_input_stream, DispatchQueue(label: "xyz.httpsocket", attributes: []));
CFWriteStreamSetDispatchQueue(_output_stream, DispatchQueue(label: "xyz.httpsocket", attributes: []));

// 4) Open streams(input/output)
if(!CFReadStreamOpen(_input_stream)) {
    close(nil);
    self._promise.reject(HTTPSocketStreamError());
    return self._promise;
}

if(!CFWriteStreamOpen(_output_stream)) {
    close(nil);
    self._promise.reject(HTTPSocketStreamError());
    return self._promise;
}

let request: CFHTTPMessage = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET" as CFString, _url as CFURL, kCFHTTPVersion1_1).takeRetainedValue();
self.request(message: request);

if let http_message = CFHTTPMessageCopySerializedMessage(request) {
    let data: Data = http_message.takeRetainedValue() as Data;
    // need some pause here
    let length = data.withUnsafeBytes{
        // 5) Write to output stream
        _output_stream!.write([=10=], maxLength: data.count)
    }

    if (length != 0) {
        return self._promise;
    }
}

忘记了"self."

if let http_message = CFHTTPMessageCopySerializedMessage(request) {
    let data: Data = http_message.takeRetainedValue() as Data;
    // need some pause here
    let length = data.withUnsafeBytes{
        // 5) Write to output stream
        self._output_stream!.write([=10=], maxLength: data.count)
    }