在NSMutableData中在前面插入字节

5

我该如何在我的NSMutableData开头插入一个字节? 我知道有一个replaceBytesInRange:方法,但那只会替换字节。 有一堆insertXAtIndex:方法,但没有一个是针对字节的。 我该怎么做? 其中一个我能想到的方法是:

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

但肯定有更好的方法。

我也尝试了这个,但它没有起作用:

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

我没有尝试过,但是使用replaceBytesInRange:withBytes:并指定零长度范围怎么样? - rmaddy
@rmaddy 我试过了,但还是不行。看看我的编辑以确保我理解你的意思。 - Milo
我猜那样行不通。它必须查看范围长度以知道从“withBytes:`”参数获取多少字节。 - rmaddy
@rmaddy 经过测试,是的,它确实可以。 - Milo
@rmaddy,你的理论是正确的,一个零长度的范围确实可以做到这一点。诀窍在于你可以指定字节的长度。 - Milo
1个回答

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

应该可以解决问题。

不行,只需将“Second!”替换为“First!”即可。 - Milo
啊,我在strlen中使用了错误的字符串。现在它为我打印出“First!Second!”。 - Gerd K

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接