关于JSContext交互后导致内存泄漏问题

2017-09-15  本文已影响664人  爱打码滴小燕子

情景:某一页面有一UIWebView,点击webView上返回按钮退回原界面。打断点发现没有走dealloc方法。

代码:

#import "BaseViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>

@protocol JSObjectProtocol <JSExport>

/**
 JS调用OC实现退出当前页面
 */
- (void)CloseView;

@end
@interface InviteViewController : BaseViewController<UIWebViewDelegate、JSObjectProtocol>

@property (nonatomic,strong)UIWebView *webView;

@end
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, kDeviceHeight-kNavigationBar-20)];
    _webView.backgroundColor=[UIColor lightGrayColor];
    _webView.mediaPlaybackRequiresUserAction = NO;
    _webView.delegate = self;
    [self.view addSubview:_webView];
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"anxinjiaohu"] = self;
    context[@"anxinactivity"] = self;
}
- (void)CloseView {
    
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        
        [self closeThisController];
    }];
}

- (void)closeThisController {
    
    if (self.isFromActivityPage == YES) {
        
        UIViewController *rootVC = self.presentingViewController;
        
        while (rootVC.presentingViewController) {
            
            rootVC = rootVC.presentingViewController;
        }
        
        [rootVC dismissViewControllerAnimated:YES completion:nil];
        
    } else {
        
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    NSLog(@"该退出了");
}

接下来运行程序会发现,dealloc方法没被调用,如果网页自动播放声音,退回去之后,声音还在不停的播放。明显对象没有释放,存在内存泄漏。那是什么导致的呢?

经排查,原因出在下面两句代码上

    context[@"anxinjiaohu"] = self;
    context[@"anxinactivity"] = self;

在这里,self被强引用了。小编又尝试使用__weak,结果发现问题还是解决不了。最后怎么解决的呢?

这里,我们需要找到context对应的控制器,然后用单例方法来替代self,即可完美解决这个问题。

将上述代码修改为:

    context[@"anxinjiaohu"] = [InviteViewController sharedInstance];
    context[@"anxinactivity"] = [InviteViewController sharedInstance];

用模拟器再次运行程序,发现调用dealloc了,证明对象销毁了。但是,发现销毁对象之后,xcode仍在不停的打印一些信息。

xcode打印的东西.png

但是用手机运行的话,则不会打印。这其实是xcode配置的问题,xcode7就不会存在。解决方法很简单:

如下图所示:

xcode配置.png
上一篇 下一篇

猜你喜欢

热点阅读