WKWebView不走dealloc 循环引用

WKWebView不走dealloc 循环引用_第1张图片
Paste_Image.png

解决方法 新增一个类 来遵守协议 设置代理属性 作为中间层,避免循环引用

#import 
#import 

@interface LEWeakScriptMessageDelegate : NSObject
@property (nonatomic, weak) id scriptDelegate;

- (instancetype)initWithDelegate:(id)scriptDelegate;
@end

#import "LEWeakScriptMessageDelegate.h"

@implementation LEWeakScriptMessageDelegate

- (instancetype)initWithDelegate:(id)scriptDelegate
{
self = [super init];
if (self) {
    _scriptDelegate = scriptDelegate;
}
return self;
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
[self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
}

- (void)dealloc
{
NSLog(@"%s",__func__);
}

然后在持有webView的控制器中的viewDidLoad方法addScriptMessageHandler;在dealloc方法中removeScriptMessageHandlerForName

- (void)addAllScriptMsgHandle{
if (myWebView) {
    [myWebView.configuration.userContentController addScriptMessageHandler:[[LEWeakScriptMessageDelegate alloc]initWithDelegate:self]name:@"show"];
    }
}

- (void)removeAllScriptMsgHandle{
if (myWebView) {
    WKUserContentController *controller = myWebView.configuration.userContentController;
    [controller removeScriptMessageHandlerForName:@"show"];
    }
}

这样的话可以解决循环引用;而且在添加手势给navigationController 拖拽侧边pop控制器也可以释放removeScriptMessageHandlerForName;
在viewDidAppear 中 add,viewDidDisappear中remove,虽然对称,但是会崩溃,说add的时候已经存在了.

如果有子类继承了这个持有webView的控制器,viewDidLoad方法中super调用,不能再add相同的handler了,会崩溃;但是可以重写协议方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message

最后如下 控制器dealloc 会调用 过度代理类也会调用dealloc


Paste_Image.png

参考文章
http://blog.cocosdever.com/2016/03/07/WKWebView-JS%E4%BA%92%E4%BA%A4%E5%BC%80%E5%8F%91%E4%B8%8E%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F/
http://www.jianshu.com/p/6ba2507445e4
http://stackoverflow.com/questions/26383031/wkwebview-causes-my-view-controller-to-leak
https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/API/Cocoa/WKUserContentController.mm

你可能感兴趣的:(WKWebView不走dealloc 循环引用)