WKWebView 与js交互不释放问题

在使用WKWebView和js交互时,会发现不走dealoc方法,也就是没有释放。经查,问题出现在注册方法那行代码,eg:

[config.userContentController addScriptMessageHandler:self name:@"close"];

config是生成WKWebView需要的配置类WKWebViewConfiguration,它注册方法是会对self引用,而我是吧WkWebView作为一个属性,这样就发生了循环引用,

界面办法发是生成一个代理类,名字为:WeakScriptMessageDelegate

WeakScriptMessageDelegate.h

#import 
#import 
@interface WeakScriptMessageDelegate : NSObject

@property (nonatomic, weak) id scriptDelegate;

- (instancetype)initWithDelegate:(id)scriptDelegate;

@end

WeakScriptMessageDelegate.m

#import "WeakScriptMessageDelegate.h"

@implementation WeakScriptMessageDelegate

- (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];
}


@end

将代码

[config.userContentController addScriptMessageHandler:self name:@"close"];

改成

[config.userContentController addScriptMessageHandler:[[JFTWeakScriptMessageDelegate alloc] initWithDelegate:self] name:@"close"];

即可。

你可能感兴趣的:(WKWebView 与js交互不释放问题)