iOS中wkwebView内存泄漏与循环引用问题详解

来自:互联网
时间:2020-05-26
阅读:

前言

现在大多数网络也面加载都会用到wkwebview,之前在使用wkwebview的时候,网上很多的基础教程使用很多只是说了怎么添加Message Handler 但是并没有告诉到家有这个内存泄漏的风险,如果你只是也没内的数据调用你压根都不会发现这个问题。没存泄漏这个问题说大不大,说小不小,严重的话话直接到时app闪退,所以还是得重视起。好下面说一下怎么解决,话不多说了,来一起看看详细的介绍吧

解决方法

1,在做网页端js交互的时候 我们都会这样去添加js

[self.customWebView.configuration.userContentController addScriptMessageHandler:self name:obj];

后面也添加了 delloc

- (void)dealloc {
 [_customWebView removeObserver:self forKeyPath:@"estimatedProgress"];
 [self removeScriptMessageHandler];
}

后来发现在加载网页的时候 pop push 多次操作 内存一直在增加,高的时候 都快200上下了,才注意到这个内存问题,
刚开始的解决方法是:

- (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 
 [self removeScriptMessageHandler];
}

后来发现问题依旧存在 delloc 依旧不走,虽然走了移除方法 ,但是在当你在pop push时候 网页没有移除掉原先占的内存,后来发现

[userContentController addScriptMessageHandler:self name:GetKeyiOSAndroid_Action];

这里userContentController持有了self ,然后
userContentController 又被configuration持有,
最终呗webview持有,然后webview是self的一个私有变量,
所以self也持有self,所以这个时候有循环引用的问题存在,
导致界面被pop或者dismiss之后依然会存在内存中。不会被释放
目前想到2个办法

1,上面我提到了 self持有self,导致的循环引用问题

我做法是重新建了一个类WKWebViewConfiguration

[[WKWebViewConfiguration alloc]init]; 

  userContentController =[[WKUserContentController alloc]init];       configuration.userContentController= userContentController; 

  webView = [[WKWebView alloc]initWithFrame:self.view.bounds configuration:configuration];

重写self方法就解决了

2,delloc 内存,

- (void)viewWillAppear:(BOOL)animated {
 [super viewWillAppear:animated];

 [_webView.configuration.userContentController addScriptMessageHandler:self name:GetKeyiOSAndroid_Action];
 [_webView.configuration.userContentController addScriptMessageHandler:self name:Upload_Action];
}

- (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];

 [_webView.configuration.userContentController removeScriptMessageHandlerForName:GetKeyiOSAndroid_Action];
 [_webView.configuration.userContentController removeScriptMessageHandlerForName:Upload_Action];
}

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

返回顶部
顶部