今天看啥  ›  专栏  ›  爱哭的僵小鱼

iOS wkwebView内存泄漏和循环引用问题

爱哭的僵小鱼  · 简书  ·  · 2018-07-12 15:51

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

}

这是网上看到的,
https://blog.csdn.net/wxs0124/article/details/78402596
最终解决了这个问题
有什么问题可以私聊我,尽力帮大家解决问题

也欢迎大家关注我的github账号 点个star
github地址




原文地址:访问原文地址
快照地址: 访问文章快照