NSData & Encodings
NSData is an immutable buffer of raw bytes: the contents of a file, a network response, an image or an encrypted blob. NSMutableData is its growable subclass. Text and bytes are different things: to go between an NSString and NSData you always choose a character encoding, almost always UTF-8.
Strings to bytes and back
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSString *text = @"Café";
NSData *utf8 = [text dataUsingEncoding:NSUTF8StringEncoding];
NSData *utf16 = [text dataUsingEncoding:NSUTF16LittleEndianStringEncoding];
NSLog(@"%lu characters", (unsigned long)text.length);
NSLog(@"UTF-8: %lu bytes", (unsigned long)utf8.length);
NSLog(@"UTF-16: %lu bytes", (unsigned long)utf16.length);
NSString *decoded = [[NSString alloc] initWithData:utf8 encoding:NSUTF8StringEncoding];
NSLog(@"decoded: %@, equal: %d", decoded, [decoded isEqualToString:text]);
}
return 0;
}4 characters
UTF-8: 5 bytes
UTF-16: 8 bytes
decoded: Café, equal: 1
é takes two bytes in UTF-8 but the other letters take one, so the four characters become five bytes. In UTF-16 every one of these characters takes two bytes.
Looking at the bytes
bytes returns a C pointer to the buffer, which you can read like any C array:
#import <Foundation/Foundation.h>
NSString *hexString(NSData *data) {
const unsigned char *bytes = data.bytes;
NSMutableString *hex = [NSMutableString string];
for (NSUInteger i = 0; i < data.length; i++) {
[hex appendFormat:@"%02x ", bytes[i]];
}
return hex;
}
int main(void) {
@autoreleasepool {
NSData *data = [@"Hi é!" dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", hexString(data));
// Building data from raw bytes
unsigned char header[] = {0x89, 'P', 'N', 'G'};
NSData *png = [NSData dataWithBytes:header length:sizeof(header)];
NSLog(@"%lu bytes: %@", (unsigned long)png.length, hexString(png));
NSData *slice = [data subdataWithRange:NSMakeRange(0, 2)];
NSLog(@"first two bytes as text: %@",
[[NSString alloc] initWithData:slice encoding:NSUTF8StringEncoding]);
}
return 0;
}48 69 20 c3 a9 21
4 bytes: 89 50 4e 47
first two bytes as text: Hi
Invalid data
Decoding bytes that aren't valid in the chosen encoding returns nil, not a garbled string. Always check:
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
unsigned char broken[] = {'o', 'k', 0xff, 0xfe}; // 0xff never appears in UTF-8
NSData *data = [NSData dataWithBytes:broken length:4];
NSString *asUTF8 = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"as UTF-8: %@", asUTF8 ?: @"(invalid UTF-8)");
NSString *asLatin1 = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding];
NSLog(@"as Latin-1: %lu characters", (unsigned long)asLatin1.length);
// Can this text be represented in ASCII?
NSLog(@"'plain' ASCII? %d", [@"plain" canBeConvertedToEncoding:NSASCIIStringEncoding]);
NSLog(@"'naïve' ASCII? %d", [@"naïve" canBeConvertedToEncoding:NSASCIIStringEncoding]);
}
return 0;
}as UTF-8: (invalid UTF-8)
as Latin-1: 4 characters
'plain' ASCII? 1
'naïve' ASCII? 0
Latin-1 maps every byte to a character, so it never fails, but the result is only meaningful if the data really was Latin-1.
Base64
Base64 turns arbitrary bytes into plain ASCII text, so binary data can travel inside JSON, URLs or email:
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSData *secret = [@"user:pa55word" dataUsingEncoding:NSUTF8StringEncoding];
NSString *encoded = [secret base64EncodedStringWithOptions:0];
NSLog(@"Basic %@", encoded);
NSData *decoded = [[NSData alloc] initWithBase64EncodedString:encoded options:0];
NSLog(@"back: %@", [[NSString alloc] initWithData:decoded encoding:NSUTF8StringEncoding]);
NSData *bad = [[NSData alloc] initWithBase64EncodedString:@"%%%" options:0];
NSLog(@"invalid input gives nil: %d", bad == nil);
}
return 0;
}Basic dXNlcjpwYTU1d29yZA==
back: user:pa55word
invalid input gives nil: 1
Note: Base64 is an encoding, not encryption: anyone can decode it.
NSMutableData
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSMutableData *packet = [NSMutableData data];
uint8_t version = 2;
[packet appendBytes:&version length:1];
[packet appendData:[@"PING" dataUsingEncoding:NSUTF8StringEncoding]];
uint8_t terminator = 0x0a;
[packet appendBytes:&terminator length:1];
NSLog(@"packet is %lu bytes", (unsigned long)packet.length);
const uint8_t *b = packet.bytes;
NSLog(@"version byte %u, last byte 0x%02x", b[0], b[packet.length - 1]);
NSLog(@"equal to itself copied? %d", [packet isEqualToData:[packet copy]]);
}
return 0;
}packet is 6 bytes
version byte 2, last byte 0x0a
equal to itself copied? 1
On Apple platforms you would typically write data to disk with [data writeToFile:path atomically:YES] and read it with [NSData dataWithContentsOfFile:path]; the playground examples stay in memory.
| Encoding constant | Meaning |
|---|---|
NSUTF8StringEncoding |
UTF-8, the default choice for files and networks |
NSUTF16StringEncoding |
UTF-16 with a byte-order mark |
NSASCIIStringEncoding |
7-bit ASCII only |
NSISOLatin1StringEncoding |
ISO 8859-1 (Western European) |
Test yourself
How many bytes is @"Café" in UTF-8?
- 4
- 5
- 8
- 6
What does initWithData:encoding: return for bytes that are invalid in that encoding?
- An empty string
- A string with ? characters
- nil
- It raises an exception
What is Base64 used for?
- Encrypting passwords
- Compressing data
- Representing binary data as ASCII text
- Sorting data