ios|ios webView的userContentController(代理方法在某些机型下仅走一次)

首先要追溯到写的注册标识符方法那里....... WKWebViewConfiguration * wkconfiguration = [[WKWebViewConfiguration alloc] init];
// userContentController 强引用了 self (控制器)
[wkconfiguration.userContentController addScriptMessageHandler:self name:@"name"];
如果没有执行对应的removeScriptMessageHandlerForName,就会造成内存泄漏,而如果移除方法写到- (void)dealloc方法里,会出现dealloc方法不走的现象也导致内存泄漏。
解决这种问题有两种方法:
一是:
addScriptMessageHandler: 写到- (void)viewWillAppear:(BOOL)animated { }方法里;
removeScriptMessageHandlerForName:写到- (void)viewWillDisappear:(BOOL)animated{ }方法里。
重点来了。。。
就是因为这样写 导致userContentController:didReceiveScriptMessage:代理方法只在第一次点击的时候会触发,再点击的时候 就会不触发 而且是在某个机型上不是所有的手机都会出现,神奇不 因为移除后跟js的交互就失效了,但是viewWillDisappear并不代表dealloc
所以这种方法不建议
二是:
新建一个类:如 WeakScriptMessageDelegate
#import #import @interface WeakScriptMessageDelegate : NSObject
@property (nonatomic,weak)id scriptDelegate;

  • (instancetype)initWithDelegate:(id)scriptDelegate;
    @end
WeakScriptMessageDelegate.m
#import "WeakScriptMessageDelegate.h" @implementation WeakScriptMessageDelegate
  • (instancetype)initWithDelegate:(id)scriptDelegate{
    self = [super init];
    if (self) {
    _scriptDelegate = scriptDelegate;
    }
    return self;
    }
  • (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    [self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
    }
    @end
【ios|ios webView的userContentController(代理方法在某些机型下仅走一次)】然后对应改成:
WKWebViewConfiguration * configuration = [[WKWebViewConfiguration alloc] init];
[configuration.userContentController addScriptMessageHandler:[[WeakScriptMessageDelegate alloc] initWithDelegate:self] name:@"name"];

    推荐阅读