Search code examples
iosmemoryuiwebviewviewdidloadmemory-warning

Prevent UIWebView allocating to much memory


I have a problem with UIWebView. I am using this component for loading normal web pages on iPad/iPhone. UIWebView is presented in modalViewController. Some pages are very memory hungry and some also have Flash content.

The problem is that sometimes on some pages I get memory warning

Received memory warning. Level=1

When this happens and when I close this modalViewController (which has page loaded in webView) than the previous view reloads itself automacially - method viewDidLoad is fired again.

I suspect that some pages in UIWebView consume to much memory and than application release memory of its views, but does not crash.

Is there a way to limit memory consumption of webView or is there any other way to avoid this memory warning?

Thanks!


Solution

  • You have very little control of the memory usage of UIWebView objects. You also have very little control of the overall system memory usage. So there is no way to avoid memory warnings. iOS expects your apps to behave properly when receiving memory warnings, so your viewDidLoad method should be written to handle rerunning after a memory warning.

    The only things you can do to limit the memory usage of a UIWebView is to have it view simple web pages. It looks like from your question, that's not an option.

    Edit: viewDidUnload is called during low-memory conditions. This method is expected to free up anything that's easy to recreate in the viewDidLoad method. Don't release the state information you want to show the user when this view is returned to the screen. Then in your viewDidLoad method check all the objects you create. If they are nil, they need to be initialized, otherwise this isn't the first time your viewDidLoad method was called, and you shouldn't initialize your objects agin.

    In other words: viewDidUnload handles low-memory situations and viewDidLoad should not assume it is run once.