Converting NSData to other types

suggest change

To String

Swift

let string = NSString(data: data, encoding: NSUTF8StringEncoding) as String? // data is UTF-8

Objective-C

NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; // data is UTF-8

To Array

bytes is a pointer to raw memory. Casting it to NSArray does not produce an array. If data holds a JSON array, parse it:

Swift

let array = (try? JSONSerialization.jsonObject(with: data as Data, options: [])) as? [Any]

Objective-C

NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];

To a byte buffer

Swift

let bytesArray = [UInt8](data as Data) // a copy of the bytes

Objective-C

// Pointer is valid only while data is alive. It is not an object.
const UInt8 *bytesArray = (const UInt8 *)data.bytes;

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents