Read IntegerType from NSInputStream

后端 未结 1 1047
陌清茗
陌清茗 2021-01-23 09:07

I am trying to write a generic function that will read an int-typed value from NSInputStream:

func read() -> T? {
    var          


        
1条回答
  •  借酒劲吻你
    2021-01-23 09:24

    The read() method requires a mutable buffer pointer:

    let n = withUnsafeMutablePointer(&buffer) { (p) in
        self.read(UnsafeMutablePointer(p), maxLength: sizeof(T))
    }
    

    The placeholder type in UnsafeMutablePointer(p) can be inferred automatically from the context.

    Note that there is a general problem with your approach: If the input stream is not connected to a real file but to some communication channel (e.g. a TCP socket, pipe, ...) then the only guarantee is that read() waits until at least one byte is read and the assertion n == sizeof(T) can fail. You have to read again in a loop until the required amount is read.

    0 讨论(0)
提交回复
热议问题