2014-07-19 20 views
11

Potrebbe spiegarmi come si legge correttamente da un NSInputStream?SOLO SWIFT - Lettura da NSInputStream

Non riesco a capire cosa sia UnsafePointer e a che cosa serve (anche per UnsafeArray).

La funzione di lettura NSInputStream ottiene un CMutablePointer che può essere riempito con un oggetto UnsafePointer.

È un vero casino confrontato con gli stream di Java.

Cosa raccomanderesti?

Grazie!

+1

se questo è un problema, per favore non confrontarlo con _Java_, e leggi le basi di _Swift_ invece: https://developer.apple.com/swift/resources/ – holex

risposta

20

L'ho capito da solo.

Guardate questo semplice codice:

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" 

Spiegazione: Il leggere firma del metodo: stream.read (< #buffer: UnsafeMutablePointer #>, maxLength: < # Int #>)

Ottiene un UnsafeMutablePointer come primo parametro, il che significa che il metodo si aspetta di ottenere un POINTER su un array di tipo UInt8 - NON sullo stesso array

Pertanto, aggiungiamo la notazione & prima del nome della variabile di buffer. & buffer == il puntatore all'oggetto matrice UInt8 denominato buffer.

Problemi correlati