关于iOS版的UIWebView的内存泄露的问题,已经存在了很长时间。一直也没有什么好的解决方法。最近因公司的一个项目,因为内存问题一直闪退。为了解决这个问题,在网上找了很多方法,但是基本上都不怎么好用问题依旧。以前也碰到过这个问题,当时的解决方法就是设置NSURLCache大小。因为iOS版当中的网络通讯默认都是通过NSURLConnection的来实现的。所以UIWebView的内部通讯也是通过NSURLConnection的来下载网页资源的。
- (BOOL)应用:(*的UIApplication)的应用didFinishLaunchingWithOptions:(NSDictionary的*)launchOptions
{
INT cacheSizeMemory = 1 * 1024 * 1024; // 4MB
INT cacheSizeDisk = 5 * 1024 * 1024; // 32MB
NSURLCache * sharedCache = [[[NSURLCache页头] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@“nsurlcache”]自动释放];
[NSURLCache setSharedURLCache:sharedCache];
}
并且在收到内存警告的时候,清除缓存内容。
- (无效)applicationDidReceiveMemoryWarning:(UIApplication的*)的应用 { [NSURLCache sharedURLCache] removeAllCachedResponses] }
以及在释放一个UIWebView的时候
_webView.delegate =零; [_webView loadHTMLString:@“”BASEURL:无]; [_webView stopLoading] [_webView removeFromSuperview] [NSURLCache sharedURLCache] removeAllCachedResponses] [_webView发布]
但是这么做基本上效果不是很大。囧啊..
今天偶然的机会看到一篇国外的博客文章,终于有种找到我想要的答案了。
原文地址是:HTTP://blog.techno-barje.fr//post/2010/10/04/UIWebView-secrets-part1-memory-leaks-on-xmlhttprequest/
有兴趣的朋友可以去看看,大概说的内容就是的Html当中的JS代码会引起内存泄露的问题。
VAR XMLHTTP =新的XMLHttpRequest(); xmlhttp.onreadystatechange =功能(){ 如果(xmlhttp.readyState == 4 && xmlhttp.status == 200){ //做你想做的结果 } }; xmlhttp.open(“GET”,“HTTP://your.domain/your.request / ...”,真正的); xmlhttp.send();
解决这个问题的方法是在webViewDidFinishLoad方法中设置如下:
[NSUserDefaults的standardUserDefaults] setInteger:0 forKey:@“WebKitCacheModelPreferenceKey”]; [NSUserDefaults的standardUserDefaults] setBool:NO forKey:@“WebKitDiskImageCacheEnabled”]; //自己添加的,原文没有提到。 [NSUserDefaults的standardUserDefaults] setBool:NO forKey:@“WebKitOfflineWebApplicationCacheEnabled”]; //自己添加的,原文没有提到。 [NSUserDefaults的standardUserDefaults]同步]。
关于NSUserDefaults的的另类用法还有比如设置的UserAgent也可以通过NSUserDefaults的来设置。