Sök…


Anmärkningar

Användbara resurser

Apple-dokumentation (NSData)

NSData.dataWithContentsOfFile ()

NSData.bytes

Skapa NSData-objekt

Använda en fil

Snabb

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

Objective-C

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

Använda ett strängobjekt

Snabb

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

Konvertera NSData till andra typer

Att stränga

Snabb

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];

Till Array

Snabb

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

Till Bytes Array

Snabb

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

Konvertera NSData till HEX-sträng

NSData kan representeras som hexadecimal sträng, liknande det den matar ut i sin description .

Snabb

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
Licensierat under CC BY-SA 3.0
Inte anslutet till Stack Overflow