Append NSInteger to NSMutableData

12

How do you append a NSInteger to NSMutableData. Something allong the lines of...

NSMutableData *myData = [[NSMutableData alloc] init];
NSInteger myInteger = 42;

[myData appendBytes:myInteger length:sizeof(myInteger)];

So that 0x0000002A will get appended to myData.

Any help appreciated.

objective-c
asked on Stack Overflow Apr 4, 2009 by holz • edited Apr 4, 2009 by holz

1 Answer

23

Pass the address of the integer, not the integer itself. appendBytes:length: expects a pointer to a data buffer and the size of the data buffer. In this case, the "data buffer" is the integer.

[myData appendBytes:&myInteger length:sizeof(myInteger)];

Keep in mind, though, that this will use your computer's endianness to encode it. If you plan on writing the data to a file or sending it across the network, you should use a known endianness instead. 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)];
answered on Stack Overflow Apr 4, 2009 by Adam Rosenfield • edited Apr 4, 2009 by Adam Rosenfield

User contributions licensed under CC BY-SA 3.0