码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2018-03-01 11:47:55      阅读:1319      评论:0      收藏:0      [点我收藏+]

标签:end   释放   oid   delegate   hand   for   view   weak   eal   

在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"];

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

标签:end   释放   oid   delegate   hand   for   view   weak   eal   

原文地址:https://www.cnblogs.com/tinych/p/8487052.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!