iOS wkwebView內存泄漏和循環引用問題

現在大多數網絡也面加載都會用到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地址

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容