zoukankan      html  css  js  c++  java
  • 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"];
    
    
  • 相关阅读:
    Easy Install详细参数
    linux.backspace乱码(转)
    RemoteFX
    netsh
    sc.exe
    WinRM和WinRS
    安全配置向导
    使用 Sconfig.cmd 配置服务器核心服务器
    FSMO
    Windows Server 2012之活动目录域服务的卸载
  • 原文地址:https://www.cnblogs.com/qqcc1388/p/8487052.html
Copyright © 2011-2022 走看看