在使用WKWebView和js交互时,会发现不走dealoc方法,也就是没有释放。经查,问题出现在注册方法那行代码,eg:
[config.userContentController addScriptMessageHandler:self name:@"close"];
config是生成WKWebView需要的配置类WKWebViewConfiguration,它注册方法是会对self引用,而我是吧WkWebView作为一个属性,这样就发生了循环引用,
界面办法发是生成一个代理类,名字为:WeakScriptMessageDelegate
WeakScriptMessageDelegate.h
#import <Foundation/Foundation.h>
#import <WebKit/WebKit.h>
@interface WeakScriptMessageDelegate : NSObject<WKScriptMessageHandler>
@property (nonatomic, weak) id<WKScriptMessageHandler> scriptDelegate;
- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate;
@end
WeakScriptMessageDelegate.m
#import "WeakScriptMessageDelegate.h"
@implementation WeakScriptMessageDelegate
- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)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"];
即可。