vikas ojha vikas ojha - 10 months ago 46
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


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