我有一个相当大的 NSData(或 NSMutableData,如果需要)对象,我想从中取出一小块并留下其余部分。由于我正在处理大量 NSData 字节,因此我不想制作大副本,而只是截断现有字节。基本上:
- NSData *source: <我想丢弃的几个字节> + <我想保留的大块字节>
- NSData *destination: <我想保留的大块字节>
NSMutableData 中有截断方法,但它们只截断它的结尾,而我想截断开头。我的想法是用以下方法做到这一点:
请注意,我在原始帖子中使用了错误的(复制)方法。我已经编辑并修复了它
- (const void *)bytes
和
- initWithBytesNoCopy:length:freeWhenDone:
但是,我试图弄清楚如何用这些来管理内存。我猜这个过程会是这样的(我把????s放在我不知道该怎么做的地方):
// 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];
谢谢您的帮助!