EXC_BAD_ACCESS on NSLog unless the NSString is manipulated and printed first
I'm trying to get a feel for objective C, so I wrote the code below to try to print the contents of a web page:
id url = [NSURL URLWithString:@"http://www.google.com"];
NSURLRequest* req = [NSURLRequest requestWithURL:url];
NSURLResponse* resp = [NSURLResponse new];
NSURLConnection* conn = [NSURLConnection new];
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:req returningResponse:&resp error:&error];
NSString* html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// printf([[html substringToIndex:50] cString]);
NSLog(html);
开发者_开发技巧
when I run this as-is, I get EXC_BAD_ACCESS
on the NSLog line. When I uncomment the second-last line it works. If I change the printf to an assignment it stops working again. I'm clearly missing something here about how the memory model works, but it seems like the commented out line shouldn't make any difference since it's creating a new string and it really seems like printf vs an assignment shouldn't make a difference. In the Xcode debugger when the program crashes I can see that html
does contain the HTML string I wanted to print.
try NSLog(@"%@", html) instead of just NSLog (html)
精彩评论