I have an NSData object of approximately 1000kB in size. Now I want to transfer this via Bluetooth. It would be better if I have, let's say, 10 objects of 100kB. It comes to mind that I should use the -subdataWithRange:
method of NSData.
I haven't really worked with NSRange. Well, I know how it works, but I can't figure out how to read from a given location with the length: 'to end of file'... I've no idea how to do that.
Some code on how to split this into multiple 100kB NSData objects would really help me out here. (it probably involves the -length
method to see how many objects should be made..?)
Thank you in advance.
The following piece of code does the fragmentation without copying the data:
NSData* myBlob; NSUInteger length = [myBlob length]; NSUInteger chunkSize = 100 * 1024; NSUInteger offset = 0; do { NSUInteger thisChunkSize = length - offset > chunkSize ? chunkSize : length - offset; NSData* chunk = [NSData dataWithBytesNoCopy:(char *)[myBlob bytes] + offset length:thisChunkSize freeWhenDone:NO]; offset += thisChunkSize; // do something with chunk } while (offset < length);
Sidenote: I should add that the chunk objects cannot safely be used after myBlob
has been released (or otherwise modified). chunk
fragments point into memory owned by myBlob
, so don't retain them unless you retain myBlob
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With