Search code examples
objective-cioscocoa-touchnsdata

Using substringFromIndex: with NSData


I am working on an NSData object that is 4840 bytes, and want to omit the first 20 bytes and fetch the rest. Are the substring methods substringFromIndex: / substringToIndex: applicable to NSData?


Solution

  • 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."
      }
    }