tags:

views:

29

answers:

1

Here is the problem:

The app crashes at the 2nd line, and I got EXC_BAD_ACCESS exception.

NSURL *url = [NSURL URLWithString:@"..."];

NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:url 
          options:NSDataReadingMapped 
            error:&error];
NSLog(@"Error: %@", error);
NSLog(@"%@", [data length]);

I got:

Error: (null)
Program received signal:  “EXC_BAD_ACCESS”.

Any idea?

+3  A: 

The length of the data is an unsigned integer, not an object, so you have to use an appropriate format specifier. So:

NSLog(@"%lu", (unsigned long)[data length]);

will work. For more information, see the format specifiers for NSLog in the documentation.

Also, you should never check error unless the method indicates an error state (see the appropriate documentation for each method that also reports errors). It may contain unexpected data even in the event that no error occurred. So:

if( !data ) {
  NSLog(@"An error must have occurred: %@, %@", error, [error userInfo]);
} else {
  NSLog(@"The data length: %lu", (unsigned long)[data length]);
}
Jason Coco