現(xiàn)在大多數(shù)網(wǎng)絡(luò)也面加載都會(huì)用到wkwebview,之前在使用wkwebview的時(shí)候拣挪,網(wǎng)上很多的基礎(chǔ)教程使用很多只是說了怎么添加Message Handler 但是并沒有告訴到家有這個(gè)內(nèi)存泄漏的風(fēng)險(xiǎn),如果你只是也沒內(nèi)的數(shù)據(jù)調(diào)用你壓根都不會(huì)發(fā)現(xiàn)這個(gè)問題肤寝。沒存泄漏這個(gè)問題說大不大育苟,說小不小,嚴(yán)重的話話直接到時(shí)app閃退醋闭,所以還是得重視起窄驹。好下面說一下怎么解決,
1证逻,在做網(wǎng)頁端js交互的時(shí)候 我們都會(huì)這樣去添加js
[self.customWebView.configuration.userContentController addScriptMessageHandler:self name:obj];
后面也添加了 delloc
- (void)dealloc {
[_customWebView removeObserver:self forKeyPath:@"estimatedProgress"];
[self removeScriptMessageHandler];
}
后來發(fā)現(xiàn)在加載網(wǎng)頁的時(shí)候 pop push 多次操作 內(nèi)存一直在增加乐埠,高的時(shí)候 都快200上下了,才注意到這個(gè)內(nèi)存問題囚企,
剛開始的解決方法是:
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self removeScriptMessageHandler];
}
后來發(fā)現(xiàn)問題依舊存在 delloc 依舊不走丈咐,雖然走了移除方法 ,但是在當(dāng)你在pop push時(shí)候 網(wǎng)頁沒有移除掉原先占的內(nèi)存龙宏,后來發(fā)現(xiàn)
[userContentController addScriptMessageHandler:self name:GetKeyiOSAndroid_Action];
這里userContentController持有了self 扯罐,然后
userContentController 又被configuration持有,
最終唄webview持有烦衣,然后webview是self的一個(gè)私有變量歹河,
所以self也持有self,所以這個(gè)時(shí)候有循環(huán)引用的問題存在掩浙,
導(dǎo)致界面被pop或者dismiss之后依然會(huì)存在內(nèi)存中。不會(huì)被釋放
目前想到2個(gè)辦法
1,上面我提到了 self持有self秸歧,導(dǎo)致的循環(huán)引用問題
我做法是重新建了一個(gè)類WKWebViewConfiguration
[[WKWebViewConfiguration alloc]init];
userContentController =[[WKUserContentController alloc]init]; configuration.userContentController= userContentController;
webView = [[WKWebView alloc]initWithFrame:self.view.bounds configuration:configuration];
重寫self方法就解決了
2厨姚,delloc 內(nèi)存,
- (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];
}
這是網(wǎng)上看到的键菱,
https://blog.csdn.net/wxs0124/article/details/78402596
最終解決了這個(gè)問題
有什么問題可以私聊我谬墙,盡力幫大家解決問題
也歡迎大家關(guān)注我的github賬號(hào) 點(diǎn)個(gè)star
github地址