27

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.

Neeku
  • 3,646
  • 8
  • 33
  • 43
Claudio Ferraro
  • 4,551
  • 6
  • 43
  • 78

3 Answers3

62

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.

3

Swift 3

let subdata1 = data?.subdata(in: 0..<20)
let subdata2 = data?.subdata(in: 20..<80)

Due to this is question is in very top of Google Search I wanna write here an example for swift

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
3
 NSData *mainData = /*This is you actual Data*/

 NSData *fPart = [mainData subdataWithRange:NSMakeRange(0, 20)];
 NSData *sPart = [mainData subdataWithRange:NSMakeRange(20, 80)];

Instead 80 you can use some dynamic - like data length

Sanjeev Rao
  • 2,247
  • 1
  • 19
  • 18
  • 1
    Why wouldn't it get 20-79? Are you sure? – Adam Casey Dec 10 '13 at 15:09
  • 1
    @AlBeebe No worries... I'm sure I've done the same thing more than once, and the fact that you noticed means that it's time to clean up obsolete comments anyway. Cheers. – Caleb Mar 05 '14 at 22:22