2

in my tab bar app where memory is getting low:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
  pageText = [NSString stringWithFormat:[webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"]];

The pageText line is causing a crash. If I comment out this line then there is no crash and I don't think it's the pageText NSString at fault.

I think this is on the final instance of the webViewDidFinishLoad and it looks like something is being released before webViewDidFinishLoad is done with it?

or there is no document.body.innerHTML for this webViewDidFinishLoad?

any ideas?

thanks in advance,

ade.

1
  • Also just found out that if I just assign pageText to document.body instead of document.body.innerHTML I get no crash. So it looks like this request has no resulting innerHTML - how can I check for this scenario...
    – ader
    Jun 22, 2010 at 14:24

1 Answer 1

3

stringByEvaluatingJavaScriptFromString: returns an autoreleased NSString. You do not need to use stringWithFormat:. Your code does not have a valid format either.

pageText = [NSString stringWithFormat:@"%@", [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];

would correct the format error, however because you are assigning pageText you run the risk of a crash later due to the autorelease.

The following is all that is necessary. NB: I am assuming that the Javascript is valid....

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [pageText release], pageText = nil;

    pageText = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"] retain];

    if (!pageText)
        // innerHTML was empty
        pageText = [[webView stringByEvaluatingJavaScriptFromString:@"document.body"] retain];
}

Note that the retain is added because you are assigning the pageText ivar instead of using a setter. Make sure you add [pageText release]; in your dealloc to prevent leaks. Be very careful when trying to access pageText elsewhere in your code as it could still be nil. Be defensive.

1
  • Thanks for not only the solution but the coherent explanation :)
    – ader
    Jun 22, 2010 at 14:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.