Reputation: 17732
So I'm trying to load a simple URL (http://www.google.com) into a web view. I had this in the application I was working with, but boiled it down to a basic application to remove other variables. I have an absolute minimal application setup, one view controller with a webview as its primary view. For code I have
-(void)viewDidLoad
{
[super viewDidLoad];
UIWebView *webView = (UIWebView*)self.view;
NSMutableString *urlString = [[NSMutableString alloc] initWithString:@"http://www.google.com"];
NSURL* url = [[NSURL alloc] initWithString:urlString];
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:url];
NSLog(@"Sending web request to %@", urlString);
[webView loadRequest:urlRequest];
[urlRequest release];
[url dealloc];
[urlString dealloc];
}
And when it loads, I get an EXC_BAD_ACCESS crash within the Web Thread. I am unsure if this is a problem related to the fact that I am working in the simulator, or something I've just screwed up with the setup.
Upvotes: 0
Views: 2025
Reputation: 17564
DO NOT CALL dealloc
. Call release
on url
and urlString
instead.
This is because other objects have references to those objects, and when you say dealloc
, you are explicitly destroying them. This is causing the EXC_BAD_ACCESS
, because when other objects try to access the url and string objects, they have already been destroyed.
This is the whole point of reference counting. YOU are done with those objects, so if you say:
[url release];
[urlString release];
You are declaring that. This decrements the count of references to those objects. But up above, you said:
NSURL* url = [[NSURL alloc] initWithString:urlString];
This means url
probably has a reference to that string. So it would have retain
ed it when you created it. So after you release the string, it does not get destroyed because url
still has a reference to it. When IT is done with it, it too will release it, and then (if no one else has claim to the object), it will automatically be dealloc
ed, because its count will have dropped to zero.
Always keep in mind who else might be using your objects when you are dealing with this sort of memory management. You can read more about it in Apple's docs.
Upvotes: 3