美文网首页
关于JSContext交互后导致内存泄漏问题

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

作者: 爱打码滴小燕子 | 来源:发表于2017-09-15 11:03 被阅读664次

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

代码:

  • 1、在VC.h里引入JS框架<JavaScriptCore/JavaScriptCore.h>,并声明JSObjectProtocol协议。方便JS调用OC方法。
#import "BaseViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>

@protocol JSObjectProtocol <JSExport>

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

@end
  • 2、该VC遵循<UIWebViewDelegate、JSObjectProtocol>协议。
@interface InviteViewController : BaseViewController<UIWebViewDelegate、JSObjectProtocol>

@property (nonatomic,strong)UIWebView *webView;

@end
  • 3、搭建界面,并设置webView的代理为self
    _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];
  • 4、在webView代理方法里设置JSContext对象
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"anxinjiaohu"] = self;
    context[@"anxinactivity"] = self;
}
  • 5、实现JS协议方法
- (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打开"Product"——"Scheme"——"Edit Scheme";
  • 选择"Arguments",在Environment Variables中添加"OS_ACTIVITY_MODE:disable"即可。

如下图所示:

xcode配置.png

相关文章

网友评论

      本文标题:关于JSContext交互后导致内存泄漏问题

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