Saturday, June 1, 2013

NSMutableData appendBytes example in Objective C (iOS).


NSMutableData appendBytes

Appends to the receiver a given number of bytes from a given buffer.

- (void)appendBytes:(const void *)bytes length:(NSUInteger)length

Parameters
bytes
A buffer containing data to append to the receiver's content.
length
The number of bytes from bytes to append.

Discussion of [NSMutableData appendBytes]
A sample using this method can be found in Working With Mutable Binary Data.

NSMutableData appendBytes example.
For example, to convert from host (your machine) to network endianness, use htonl():

uint32_t theInt = htonl((uint32_t)myInteger);
[myData appendBytes:&theInt length:sizeof(theInt)];

Example of [NSMutableData appendBytes].
NSMutableData *data = [NSMutableData data];
char bytesToAppend[5] = {0x01, 0xf0, 0x64, 0x0, 0x6a};
[data appendBytes:bytesToAppend length:sizeof(bytesToAppend)];

NSMutableData appendBytes example.
To store:

SInt16 *frames = ...;
NSUInteger length = ...;    // Assuming number of elements in frames, not bytes!  
NSMutableData *data = [[NSMutableData alloc] initWithCapacity:0];
[data appendBytes:(const void *)frames length:length * sizeof(SInt16)];
To retrieve:

SInt16 *frames = (SInt16 *)[data bytes];
NSUInteger length = [data length] / sizeof(SInt16);

End of NSMutableData appendBytes example article.