New NSData with range of old NSData maintaining bytes.
Posted
by umop
on Stack Overflow
See other posts from Stack Overflow
or by umop
Published on 2010-04-07T21:57:30Z
Indexed on
2010/06/16
2:22 UTC
Read the original article
Hit count: 366
I have a fairly large NSData (or NSMutableData if necessary) object which I want to take a small chunk out of and leave the rest. Since I'm working with large amounts of NSData bytes, I don't want to make a big copy, but instead just truncate the existing bytes. Basically:
- NSData *source: < a few bytes I want to discard > + < big chunk of bytes I want to keep >
- NSData *destination: < big chunk of bytes I want to keep >
There are truncation methods in NSMutableData, but they only truncate the end of it, whereas I want to truncate the beginning. My thoughts are to do this with the methods:
- getBytes:range:
and
- initWithBytesNoCopy:length:freeWhenDone:
However, I'm trying to figure out how to manage memory with these. I'm guessing the process will be like this (I've placed ????s where I don't know what to do):
void *buffer
// Get range of bytes
[source getBytes:buffer range:NSMakeRange(myStart, myLength)];
// 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:buffer
length:myLength
freeWhenDone:YES];
Thanks for the help!
© Stack Overflow or respective owner