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"];
    
    
  • 相关阅读:
    Jmeter使用自定义编写代码
    Jmeter关于断言
    Jmeter之函数助手
    无界面运行Jmeter压测脚本 --后知者
    接口测试全流程总结
    全面的功能测试点总结
    简述核心网
    题1:一个手机H5测试页面,页面上有一个文本输入框和一个次数的按键---测试用例编写
    2019 版_Python 常见的 170 道面试题全解析:编码规范
    2019 版_Python 常见的 170 道面试题全解析:语言特性
  • 原文地址:https://www.cnblogs.com/qqcc1388/p/8487052.html
Copyright © 2011-2022 走看看