UIWebView

UIWebView内存泄露问题解决方法

2016-07-11  本文已影响574人  a乾坤大挪移a

关于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来设置。

上一篇 下一篇

猜你喜欢

热点阅读