UIWebView关于XMLHttpRequest的内存泄漏
最近在应用中嵌入HTML页面时,导致应用常常崩溃,用insturmemt检测发现存在内存泄露。但不是所有的页面多存在这个问题,上网查了一下,发现是javascript代码导致内存泄露。
通常情况下,当你在UIWebView执行这个Javascript时,你将有一个大的内存使用和泄漏大量的数据。
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();
解决方法:
事实上,导致此泄漏的关键属性是的 WebKitCacheModelPreferenceKey。当你在一个UIWebView打开一个链接,这个属性被自动设置为“1”值 。因此,解决的办法是每当你打开一个链接时把它设回0:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
}