iOS 添加WKWebView导致控制器无法释放的问题

在WkWebView与JavaScript交互中,经常会在原生中注入MessageHandler,app中注入MessageHandler的方法

    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.userContentController = [WKUserContentController new];
    //注入handler
    [config.userContentController addScriptMessageHandler:self name:@"HandlerName"];

这里我们发现在向JS中注入handler的时候强引用了self,最终导致内存泄漏

解决方法 添加一个新类 WeakScriptMessageDelegate

@interface WeakScriptMessageDelegate : NSObject<WKScriptMessageHandler>

@property (nonatomic, weak) id<WKScriptMessageHandler> scriptDelegate;

- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate;

@end

@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

使用 添加了下面这行代码之后ViewController就会调用dealloc方法,此时ViewController已经正常释放。但是WeakScriptMessageDelegate没有释放,需要在dealloc中将WeakScriptMessageDelegate释放掉。

    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.userContentController = [WKUserContentController new];
    //注入handler
    [config.userContentController addScriptMessageHandler:[[WeakScriptMessageDelegate alloc] initWithDelegate:self] name:@"HandlerName"];

释放WeakScriptMessageDelegate 在dealloc方法中实现

    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"HandlerName"];

posted @ 2018-03-01 10:07  qqcc1388  阅读(850)  评论(0编辑  收藏  举报