Unable to Completely Reclaim Memory Usage from UIW

2019-04-11 00:32发布

I have the following sample code (using ARC) which adds a UIWebView as a subview and subsequently removes it (toggled by a tap gesture on the screen):

- (void)toggleWebViewLoading:(UITapGestureRecognizer *)sender
{
    if (webView == nil)
    {
        webView = [[UIWebView alloc] initWithFrame:CGRectMake(0.0f, 100.0f, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 100.0f)];
        [webView loadRequest:[[NSURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:@"http://www.google.ca"]]];
        [self.view addSubview:webView];
    }
    else
    {
        [webView removeFromSuperview];
        webView = nil;
    }
}

When the app initially loads with a blank UIView, it consumes approximately 1.29 MB (live bytes reading from Instruments.app). Tapping on the blank UIView causes the toggleWebViewLoading: function to fire which in turn creates a new UIWebView, loads Google, and adds it as a subview. Once this sequence of operations have been completed, the memory usage is approximately 3.61 MB. Tapping again executes the second part of toggleWebViewLoading: which removes the UIWebView from its superview and sets it to nil. At this point the memory consumption has dropped to 3.38 MB.

My question is, how can I completely reclaim the memory from UIWebView (i.e. have the memory consumption return to its initial value of 1.29 MB or something similar after the the UIWebView has been removed and set to nil)?

Other Relevant Information

Before someone asks why I care so much about ~2 MB of memory savings, I have I much more complicated situation using Xamarin/MonoTouch where 10+ UIWebView's are consuming 200 MB+ of memory and I can't ever seem to reclaim all of the memory when it is no longer needed. I think the answer boils down to this simple question.

1条回答
Bombasti
2楼-- · 2019-04-11 01:26

I would suggest monitoring how many threads you have active. UIWebView spawns several threads for itself. I expect they are not cleaned up properly once the UIWebView is deallocated, but it's just a hunch.

查看更多
登录 后发表回答