温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

iOS中wkwebView内存泄漏与循环引用问题的示例分析

发布时间:2021-08-19 14:41:38 来源:亿速云 阅读:144 作者:小新 栏目:移动开发

这篇文章给大家分享的是有关iOS中wkwebView内存泄漏与循环引用问题的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

解决方法

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];
}

感谢各位的阅读!关于“iOS中wkwebView内存泄漏与循环引用问题的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI