3

I want to check the last 2 bytes of files in my app to make sure they are not corrupt .jpg's

rangeOfData:options:range: looks like a good option, but I am having a hard time figuring out how to get a proper NSRange. The range I am looking for is starting near the end of the NSData, up to the end.

Here is what I have so far:

NSData *imageData = [NSData dataWithContentsOfFile:filePath];
NSRange range = {([imageData length]-8),[imageData length]};
NSString *str = @"FFD9";
NSData *jpgTest = [str dataUsingEncoding:NSUTF8StringEncoding];
NSRange found = [imageData rangeOfData:jpgTest options:NSDataSearchBackwards range:range];

Here is the error I get:

** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSConcreteData rangeOfData:options:range:]: range {14954, 14962} enxceeds data length 14962'

How do I properly get the range to search the last few bytes of my NSData?

jscs
  • 63,694
  • 13
  • 151
  • 195
Slee
  • 27,498
  • 52
  • 145
  • 243

1 Answers1

8

The second member of NSRange is not the end point of the range but its length. So in your case it should be:

NSRange range = {([imageData length]-8), 8};
Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
  • I guess I could have just looked at the documentation: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html - thanks! – Slee Jun 13 '12 at 11:29
  • Indeed. I find that the documentation answers almost all questions I have. – Ole Begemann Jun 13 '12 at 11:30