vikas ojha vikas ojha - 1 year ago 103
iOS Question

Using substringFromIndex: with NSData

I am working on an

object that is 4840 bytes, and want to omit the first 20 bytes and fetch the rest. Are the substring methods
applicable to

Answer Source

You are close, NSData has a method subdataWithRange:. You can make a range with the function NSMakeRange and then use that range to produce an NSData trimmed as you like.

An example:

// Create NSData
NSString* myString = @"Lorem ipsum dolor sit amet, consectetur cras amet.";
NSData*   myData   = [myString dataUsingEncoding:NSUTF8StringEncoding];
if (myData != nil && myData.length > 20) {

  // Create trimmed NSData
  NSData* newData = [myData subdataWithRange:NSMakeRange(20, myData.length - 20)];
  if (newData != nil) {

    // Test
    NSString* newString = [[NSString alloc] initWithData: newData 
                                                encoding: NSUTF8StringEncoding];
    NSLog(@"%@", newString);
    // -> "t amet, consectetur cras amet."
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download