美文网首页
28期_iOS_WKWebView的内存问题

28期_iOS_WKWebView的内存问题

作者: 萧修 | 来源:发表于2023-08-29 01:00 被阅读0次

内存问题主要讨论WKUserContentController添加

下面导致的问题
WKUserContentController持有self,
WKWebViewConfiguration持有WKUserContentController
WkWebView持有WKWebViewConfiguration
self持有WkWebView

[userCC addScriptMessageHandler:self name:@"nativeObj"];

循环持有导致的内存无法释放,表现来看是dealloc没有执行

- (void)dealloc
{
    NSLog(@"dealloc");
}

解决方案

WKUserContentController持有self,中间建立弱引用weak

  • 核心代码

- .h
@interface WeakWebScriptMessageDelegate : NSObject<WKScriptMessageHandler>

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

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

@end

  • .m
@implementation WeakWebScriptMessageDelegate

- (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];
}

-(void)dealloc{
    NSLog(@"%@ -- dealloc",self.class);
}
 WeakWebScriptMessageDelegate *de = [[WeakWebScriptMessageDelegate alloc]initWithDelegate:self];
[configuration.userContentController addScriptMessageHandler:de name:@"getUserId"];

在引用地方,将self被里面的scriptDelegate持有,因为scriptDelegate是weak修饰,
因此userContentController强持有WeakWebScriptMessageDelegate
WeakWebScriptMessageDelegate弱持有self

控制器dealloc可以正常打印,但是WeakWebScriptMessageDelegate没有被释放,因为WeakWebScriptMessageDelegate中注册了一些name,需要在dealloc移除

- (void)dealloc
{
    NSLog(@"dealloc");
    if (@available(iOS 14.0, *)) {
        [[_webView configuration].userContentController removeAllScriptMessageHandlers];
    } else {
        // Fallback on earlier versions
    }
    
    //[[_webView configuration].userContentController removeScriptMessageHandlerForName:@"closeMe"];
}

相关文章

网友评论

      本文标题:28期_iOS_WKWebView的内存问题

      本文链接:https://www.haomeiwen.com/subject/lhrtmdtx.html