關(guān)于使用WKWebView時(shí),ViewController不調(diào)用dealloc方法的記錄
在當(dāng)前的項(xiàng)目中,會(huì)嵌入很多的H5頁面,所以就考慮封裝一個(gè)Controller,用于完全的顯示H5頁面。基于當(dāng)前項(xiàng)目對(duì)iOS版本的支持在iOS8.0之上,所以選用WKWebView
。
很正常的在ViewDidLoad
中初始化,設(shè)置WKWebView
- (void)setupWKWebView {
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKUserContentController *controller = [[WKUserContentController alloc] init];
configuration.userContentController = controller;
self.contentWKWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 64, SCREENW, SCREENH - NAVIAGTION_HEIGHT)
configuration:configuration];
self.contentWKWebView.UIDelegate = self;
self.contentWKWebView.navigationDelegate = self;
self.contentWKWebView.allowsBackForwardNavigationGestures = YES;
// 監(jiān)聽進(jìn)度條
[self.contentWKWebView addObserver:self
forKeyPath:@"estimatedProgress"
options:NSKeyValueObservingOptionNew context:nil];
// 注冊(cè)JS交互對(duì)象
WKUserContentController *controller = self.contentWKWebView.configuration.userContentController;
[controller addScriptMessageHandler:self name:@"vhswebview"];
}
然后加載H5頁面,一切看著都很正常,但是經(jīng)過多次測(cè)試,發(fā)現(xiàn)對(duì)應(yīng)的- (void)dealloc;
一次都沒有調(diào)用,所以必然出現(xiàn)了內(nèi)存泄漏。檢查該Controller
代碼,發(fā)現(xiàn)諸如block的循環(huán)引用,代理等地方都沒有問題。
最后猜測(cè)是否是注冊(cè)JS交互對(duì)象的時(shí)候,將對(duì)象本身self
傳給MessageHandler
導(dǎo)致的。后面查詢了一些資料,發(fā)現(xiàn)在Apple的development中提到了需要移除JS交互對(duì)象removeScriptMessageHandlerForName
。
所以將頁面關(guān)閉WKWebView
的Controller
的時(shí)候,就去移除JS交互對(duì)象
WKUserContentController *controller = self.contentWKWebView.configuration.userContentController;
[controller removeScriptMessageHandlerForName:@"vhswebview"];
最后,就可以在關(guān)閉頁面后調(diào)用- (void)dealloc
了。