如何在Swift中的NSNetService上使用getInputStream()?

时间:2015-11-20 15:16:57

标签: swift pointers nsstream nsnetservice

我正在尝试为NSInputStream上的Bonjour连接设置NSOutputStreamNSNetService。 getInputStream方法需要类型为UnsafeMutablePointer<NSInputStream?>的参数:

public func getInputStream(inputStream: UnsafeMutablePointer<NSInputStream?>, outputStream: UnsafeMutablePointer<NSOutputStream?>) -> Bool

但是当我这样做时,inputStream和outputStream保持为nil并且成功为false:

    let inputStream:UnsafeMutablePointer<NSInputStream?> = nil
    let outputStream:UnsafeMutablePointer<NSOutputStream?> = nil

    var succes = service.getInputStream(inputStream, outputStream: outputStream)

另一个问题是我无法将其作为'NSInputStream'来处理,因为它的类型为'UnsafeMutablePointer'。当我尝试这个时,我收到以下错误:

Error:(52, 13) value of type 'UnsafeMutablePointer<NSInputStream?>' (aka 'UnsafeMutablePointer<Optional<NSInputStream>>') has no member 'delegate'

在swift中处理这些可变指针类型的正确方法是什么?非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:6)

你的指针是nil,因为你没有为它们分配内存。 但更简单的解决方案是将NSIn/OutputStream?变量作为传递 inout-argument with &

var inputStream : NSInputStream?
var outputStream : NSOutputStream?

let success = service.getInputStream(&inputStream, outputStream: &outputStream)