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.
Asked
Active
Viewed 2.5k times
27

Neeku
- 3,646
- 8
- 33
- 43

Claudio Ferraro
- 4,551
- 6
- 43
- 78
-
1use `NSData`'s `-(NSData *)subdataWithRange:(NSRange)range;` – Jan 20 '12 at 09:52
3 Answers
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
-
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