webView 記憶體洩漏

Eidesen發表於2016-05-24

*

轉自:http://kimsungwhee.com/ios7-uiwebview%E5%86%85%E5%AD%98%E6%B3%84%E9%9C%B2%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95/ 
關於iOS的UIWebView記憶體洩露的問題,已經存在了很長時間。一直也沒有什麼好的解決方法。最近因公司的一個專案,因為記憶體問題一直閃退。為了解決這個問題,在網上找了很多方法,但是基本上都不怎麼好用問題依舊。以前也碰到過這個問題,當時的解決方法就是設定NSURLCache大小。因為iOS當中的網路通訊預設都是通過NSURLConnection來實現的。所以UIWebView內部通訊也是通過NSURLConnection來下載網頁資源的。
-(BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    int cacheSizeMemory = 1*1024*1024; // 4MB
    int cacheSizeDisk = 5*1024*1024; // 32MB
    NSURLCache *sharedCache = [[[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"] autorelease];
    [NSURLCache setSharedURLCache:sharedCache];
}
並且在收到記憶體警告的時候,清除快取內容。
-(void)applicationDidReceiveMemoryWarning:(UIApplication*)application
{
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}
以及在釋放UIWebView的時候
_webView.delegate = nil;
[_webView loadHTMLString:@"" baseURL:nil];
[_webView stopLoading];
[_webView removeFromSuperview];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
[_webView release];
但是這麼做基本上效果不是很大。囧啊。。
今天偶然的機會看到一篇國外的Blog文章,終於有種找到我想要的答案了。
原文地址是:http://blog.techno-barje.fr//post/2010/10/04/UIWebView-secrets-part1-memory-leaks-on-xmlhttprequest/
有興趣的朋友可以去看看,大概說的內容就是Html當中的js程式碼會引起記憶體洩露的問題。
var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      // Do whatever you want with the result
    }
  };
  xmlhttp.open("GET", "http://your.domain/your.request/...", true);
  xmlhttp.send();
解決這個問題的方法是在webViewDidFinishLoad方法中設定如下:
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitDiskImageCacheEnabled"];//自己新增的,原文沒有提到。
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitOfflineWebApplicationCacheEnabled"];//自己新增的,原文沒有提到。
    [[NSUserDefaults standardUserDefaults] synchronize];
關於NSUserDefaults的另類用法還有比如設定UserAgent也可以通過NSUserDefaults來設定。

*

相關文章