Question

I have ios application. Some view controllers contain webviews. Everything works nice ,except one prolem:

When application is launched and i do not use it for some minutes and than continue my work, it works properly, but when i want to load viewcontroller with webview, it crashes with SIGKILL error. There are no problems with other viewcontrollers after some break. Here is the code which i use for webviews:

_webView = [[UIWebView alloc] initWithFrame:self.view.bounds)];
[self.view addSubview:_webView];
_webView.userInteractionEnabled = NO;
[_webView release];
// here is the local page, the same happens if i load internet page..
NSString *path = [[NSBundle mainBundle] pathForResource:@"localpage" ofType:@"html"];
_url = [NSURL fileURLWithPath:path];
[_webView loadRequest:[NSURLRequest requestWithURL:_url]];

So the question is why application crashes only trying to load viewcontrollers with webviews after some break ?

Thanks.

Was it helpful?

Solution

Your code here is very dangerous:

_webView = [[UIWebView alloc] initWithFrame:self.view.bounds)];
[self.view addSubview:_webView];
_webView.userInteractionEnabled = NO;
[_webView release];

I assume that _webView is an ivar. First, don't access your ivars directly except in init and dealloc. Direct ivar access is the #1 cause of crashes. It's just too easy to do it wrong, and you're doing it wrong here. You're releasing your ivar before you're done with it. You're betting on the view to hold it for you, which may or may not happen. For instance, if the view is unloaded (which can happen when you're off screen), then _webView becomes a dangling pointer. The correct code here is (assuming webView is a retain property):

self.webView = [[[UIWebView alloc] initWithFrame:self.view.bounds)] autorelease];
[self.view addSubview:self.webView];
self.webView.userInteractionEnabled = NO;

You are also under-retaining _url, which may cause crashes if you access _url outside of this code. Again, switching to accessors will fix that.

self.url = [NSURL fileURLWithPath:path];
[self.webView loadRequest:[NSURLRequest requestWithURL:self.url]];

Note that this issue, and many others, go away very easily if you switch to ARC. Beyond being easier to write with fewer crashes, ARC code is almost always faster than the equivalent correctly-written manual memory management. You should absolutely switch to ARC unless you have to support iPhoneOS 3.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top