App crashes when access the length of [NSData dataWithContentsOfURL:url]
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 leng开发者_运维技巧th]);
I got:
Error: (null)
Program received signal: “EXC_BAD_ACCESS”.
Any idea?
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]);
}
精彩评论