13

Could you please explain me how do I read properly from an NSInputStream?

I couldn't understand what is UnsafePointer and what's the use of it (also for UnsafeArray).

The NSInputStream read function gets an CMutablePointer which can be filled with an UnsafePointer object.

It's a real mess comparing to Java's Streams.

What would you recommend ?

Thank you!

johni
  • 5,342
  • 6
  • 42
  • 70
  • 2
    if that is mess, please don't compare it with _Java_, and read the basics of the _Swift_ instead: https://developer.apple.com/swift/resources/ – holex Aug 13 '14 at 11:24

1 Answers1

23

I have figured it out myself.

Look at this simple code:

let data: NSData = "Jonathan Yaniv.".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
let stream: NSInputStream = NSInputStream(data: data)

var buffer = [UInt8](count: 8, repeatedValue: 0)

stream.open()

if stream.hasBytesAvailable {
    let result :Int = stream.read(&buffer, maxLength: buffer.count)
}

//  result = 8 -- because of the size of the buffer.
//  buffer contains the first 8 bytes repreenting the word "Jonathan"

Explanation: The read method signature: stream.read(<#buffer: UnsafeMutablePointer#>, maxLength: <#Int#>)

It gets a UnsafeMutablePointer as a first parameter, which means the method expects to get a POINTER to an array of type UInt8 - NOT the array itself

Therefore, we add the & notation before the name of the buffer variable. &buffer == the pointer to the UInt8 array object named buffer.

johni
  • 5,342
  • 6
  • 42
  • 70
  • Really hard to find in the documentation that using the & operator with an array returns an UnsafeMutablePointer. Without that knowledge it's really hard to figure out how to do what you did. So thanks! – Michael Welch Jul 12 '18 at 21:33