Insert bytes at front in NSMutableData

insert, nsdata, nsmutabledata, objective-c

Solution

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

ought to do the trick.

Problem

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!" ```

Original source