当前位置: 移动技术网 > IT编程>移动开发>IOS > iOS中wkwebView内存泄漏与循环引用问题详解

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

2019年07月24日  | 移动技术网IT编程  | 我要评论

软件自学网,87年西游记春晚高清,赶快造句

前言

现在大多数网络也面加载都会用到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];
}

这篇文章: 最终解决了这个问题

总结

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网