在使用WKWebView
時憎兽,發(fā)現(xiàn)當前控制器pop完之后沒有執(zhí)行dealloc
方法冷离,存在內(nèi)存泄漏。
首先排查了一下blcok
中是否存在循環(huán)引用纯命,發(fā)現(xiàn)并沒有西剥,使用Instruments
的leaks
工具也沒有發(fā)現(xiàn)相關(guān)的內(nèi)存泄漏。然后我留意到在viewDidLoad
方法中調(diào)用了[_webview.configuration.userContentController addScriptMessageHandler:self name:@"xx"];
方法亿汞,并實現(xiàn)代理方法- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
瞭空,在dealloc
方法中調(diào)用對應(yīng)的[_webview.configuration.userContentController removeScriptMessageHandlerForName:@"xx"];
移除方法,但是dealloc
并沒有執(zhí)行疗我。
解決辦法:不在viewDidLoad
和dealloc
方法中添加和移除咆畏,改為在控制器將要顯示和消失的方法中添加和移除。
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[_webview.configuration.userContentController addScriptMessageHandler:self name:@"xx"];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[_webview.configuration.userContentController removeScriptMessageHandlerForName:@"xx"];
}
ps:在使用WKWebView
時吴裤,通過js
調(diào)用原生方法旧找,可以攔截url
,也可以用上面這種方法麦牺。
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者