Ricerca…


Osservazioni

Risorse utili

Documentazione Apple (NSData)

NSData.dataWithContentsOfFile ()

NSData.bytes

Creazione di oggetti NSData

Utilizzando un file

veloce

let data = NSData(contentsOfFile: filePath) //assuming filePath is a valid path

Objective-C

NSData *data = [NSData dataWithContentsOfFile:filePath]; //assuming filePath is a valid path

Utilizzando un oggetto String

veloce

let data = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding) //assuming string is a String object

Objective-C

NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; //assuming string is a String object

Conversione di NSData in altri tipi

Accordare

veloce

let string = String(NSString(data: data, encoding: NSUTF8StringEncoding)) //assuming data is a valid NSData object

Objective-C

NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; //assuming data is a valid NSData object
[string release];

Array

veloce

let array = data.bytes as! NSMutableArray //assuming data is a valid NSData object

Objective-C

NSMutableArray *array = (NSMutableArray *)[data bytes]; //assuming data is a valid NSData object

Alla matrice di byte

veloce

let bytesArray = data.bytes as! UInt8 //assuming data is a valid NSData object

Objective-C

UInt8 *bytesArray = (UInt8 *)data.bytes; //assuming data is a valid NSData object

Conversione da NSData a stringa HEX

NSData può essere rappresentato come una stringa esadecimale, simile a ciò che emette nel suo metodo di description .

veloce

extension NSData {

    func hexString() -> String {
        return UnsafeBufferPointer<UInt8>(start: UnsafePointer<UInt8>(bytes), count: length)
            .reduce("") { $0 + String(format: "%02x", $1) }
    }

}

Objective-C

@implementation NSData (HexRepresentation)

- (NSString *)hexString {
    const unsigned char *bytes = (const unsigned char *)self.bytes;
    NSMutableString *hex = [NSMutableString new];
    for (NSInteger i = 0; i < self.length; i++) {
        [hex appendFormat:@"%02x", bytes[i]];
    }
    return [hex copy];
}

@end


Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow