具有旧NSData维护字节范围的新NSData

umo*_*mop 2 truncate nsdata nsmutabledata

我有一个相当大的NSData(或NSMutableData,如果有必要)对象,我想从一个小块中取出并离开其余部分.由于我正在使用大量的NSData字节,我不想制作大的副本,而只是截断现有的字节.基本上:

  • NSData*source:<我要丢弃的几个字节> + <我要保留的大块字节>
  • NSData*destination:<我要保留的大块字节>

NSMutableData中有截断方法,但它们只截断它的结尾,而我想截断开头.我的想法是用这些方法做到这一点:

请注意,我在原始发布中使用了错误的(复制)方法.我已经编辑并修复了它

- (const void *)bytes
Run Code Online (Sandbox Code Playgroud)

- initWithBytesNoCopy:length:freeWhenDone:
Run Code Online (Sandbox Code Playgroud)

但是,我正在试图弄清楚如何用这些管理内存.我猜这个过程会是这样的(我把它放在哪里,我不知道该怎么做):

// Get bytes
const unsigned char *bytes = (const unsigned char *)[source bytes];

// Offset the start
bytes += myStart;

// Somehow (m)alloc the memory which will be freed up in the following step
?????

// Release the source, now that I've allocated the bytes
[source release];

// Create a new data, recycling the bytes so they don't have to be copied
NSData destination = [[NSData alloc]
                      initWithBytesNoCopy:bytes
                      length:myLength
                      freeWhenDone:YES];
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助!

all*_*tom 5

这是你想要的吗?

NSData *destination = [NSData dataWithBytes:((char *)source.bytes) + myStart
                                     length:myLength];
Run Code Online (Sandbox Code Playgroud)

我知道你说"我不想制作一个大副本",但这只是你getBytes:length:在你的例子中做的同一副本,所以这对你来说可能没问题.

还有replaceBytesInRange:withBytes:length:,你可能会这样使用:

[source setLength:myStart + myLength];
[source replaceBytesInRange:NSMakeRange(0, myStart)
                  withBytes:NULL
                     length:0];
Run Code Online (Sandbox Code Playgroud)

但是文档没有说明该方法是如何工作的(没有性能特征),并且source需要是一个NSMutableData.