5

How can I insert a byte at the beginning of my NSMutableData? I understand that there is a replaceBytesInRange: method but that will just replace the bytes. There is a bunch of insertXAtIndex: methods but none are for bytes. How can I do this? One way I can think of doing this is:

NSMutableData *theData = [NSMutableData dataWithBytes:myByte];
[theData appendData:myOriginalData];
myOriginalData = nil;

But there must be a better way.

I also tried this but it didn't work:

char *sec = "Second!";
char *fir = "First!";

NSMutableData *theData = [NSMutableData dataWithBytes:(const void *)sec length:7];
[theData replaceBytesInRange:NSMakeRange(0, 0) withBytes:(const void *)fir];

NSString *str1 = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
NSLog(@"%@", str1); //Prints "Second!"
Milo
  • 5,041
  • 7
  • 33
  • 59
  • I haven't tried but what about using `replaceBytesInRange:withBytes:` but specify a zero-length range? – rmaddy Jul 08 '14 at 01:09
  • @rmaddy I tried that but it didn't work either. See my edit to make sure I know what you meant. – Milo Jul 08 '14 at 01:17
  • I guess that won't work. It must look at the range length to know how many bytes to get from the 'withBytes:` parameter. – rmaddy Jul 08 '14 at 01:21
  • @rmaddy After testing it, yes it does. – Milo Jul 08 '14 at 01:22
  • @rmaddy you were right on your theory that a zero length range would do it. The trick was that you can specify the length of the bytes. – Milo Jul 08 '14 at 02:28

1 Answers1

7
[theData replaceBytesInRange:NSMakeRange(0, 0) withBytes:(const void *)fir length:strlen(fir)];

ought to do the trick.

rayryeng
  • 102,964
  • 22
  • 184
  • 193
Gerd K
  • 2,933
  • 1
  • 20
  • 23