Memory leak when using WKScriptMessageHandler

前端 未结 4 974
别跟我提以往
别跟我提以往 2021-02-02 00:36

Not sure if I hit a bug in WebKit or I am doing something horribly wrong, but I can\'t figure out how to use WKScriptMessageHandler without causing wha

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-02 01:25

    To fix a retain cycle you can use next common solution that is based on NSProxy for any protocols:

    @interface WeakProxy: NSProxy
    
    @property (nonatomic, weak) id object;
    
    @end
    
    @implementation WeakProxy
    
    + (instancetype)weakProxy:(id)object {
        return [[WeakProxy alloc] initWithObject:object];
    }
    
    - (instancetype)initWithObject:(id)object {
        self.object = object;
        return self;
    }
    
    - (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
        return [self.object methodSignatureForSelector:selector];
    }
    
    - (void)forwardInvocation:(NSInvocation *)invocation {
        [invocation invokeWithTarget:self.object];
    }
    
    @end
    

    And somewhere in your code you can write:

    let proxy = (id)[WeakProxy weakProxy:self];
    [configuration.userContentController addScriptMessageHandler:proxy name:KLoginResponseHandler];
    

提交回复
热议问题