tags:

views:

209

answers:

1

Hi,

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.

A: 

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.

falconcreek
Thanks for not only the solution but the coherent explanation :)
ade