iOS 8 UIWebView memory management

2020-06-18 02:56发布

I have a hierarchical application (NavigationController) with a simple table view in a role of the root controller. Each time you select any cell, you have got a new View with some information about the details (managed by DetailViewController). On the side of DetailViewController's view I have a UIWebView to display data from Internet. But the problem happens when I look at memory usage. Each new opened view of DetailViewController with its content loaded from the web via UiWebView brings more memory using coefficient. I'd like to unload everything and release memory allocated for that data when I get back to my root controller's view.

How do I manage that issue? I tried to stopLoading: UIWebView's instance method to save some memory, but it doesn't solve the problem either. As well as I don't completely understand ARC process of work, I can't ensure myself if it is normally to have an increased memory using coefficient with each new opened detail view.

Thank you in advance!

1条回答
The star\"
2楼-- · 2020-06-18 03:03

A few things to note. UIWebView "leaks". It has been leaking since at least iOS4. With every large page load, it seems to grow, and the memory is not replenished fully right when the UIWebView object itself is released. Whether this memory remains in a cache and is released when really needed, or a leak, I have not been able to answer correctly. This has somewhat improved over the years, but still can be seen using Instruments' memory allocation graph.

Let's start at the basics. Before you start making changes to your design, try to use Instruments to see what exactly is leaking. You can also subclass your views and view controllers, implement their dealloc methods and ensure that they are being released correctly when expected. Many times, especially when blocks are involved, people create retain cycles, that cause huge memory leaks. Do this first.

Here are a few recommendations from my experience working with WebKit:

  • Reuse the web view as much as possible. If you can, use the same object and just add it as subview of the view controllers' views.
  • We noticed that the most we could drain from the web view was opening a blank page before releasing the UIWebView object.
  • iOS8 supports a new model with working with WebKit: WKWebView (WebKit2). In this model, the web content is managed and drawn off-process, and the memory is "leaked" in that process. When needed, the OS will kill these WebKit process, thus allowing your app to run. You can try this and see if you have improvements.
查看更多
登录 后发表回答