Copy a part of NSData byte array to another NSData type

Claudio Ferraro picture Claudio Ferraro · Jan 20, 2012 · Viewed 23.2k times · Source

I have an original NSData type which contains let's say 100 bytes. I want to get 2 other NSData types. The first containing the first 20 bytes of the 100, and the second one containing the other 80. They should be copied from the original NSData. Sorry if I wasn't so clear, but I'm pretty new with Objective-C.

Answer

user971401 picture user971401 · Jan 20, 2012

You can use NSData's -(NSData *)subdataWithRange:(NSRange)range; to do that.
From your example, here is some code :

// original data in myData
NSData *d1 = [myData subdataWithRange:NSMakeRange(0, 20)];
NSData *d2 = [myData subdataWithRange:NSMakeRange(20, 80)];

Of course, the ranges are immediate here, you will probably have to do calculations, to make it work for your actual code.