iOS 懒加载为什么不起作用

2017-05-04  本文已影响45人  SailorGa

iOS 开发懒加载是很常用的;顾名思义,有些变量我们希望在需要的时候才加载(效率低,占用内存小)。其实懒加载就是重写其getter方法,就是在开发中,当程序中需要利用的资源时。在程序启动的时候不加载资源,只有在运行当需要一些资源时,再去加载这些资源。


出了问题特此记录

声明:

@property (strong, nonatomic) WKWebViewConfiguration *config;

** getter方法:**

- (WKWebViewConfiguration *)config
{
    if (!_config)
    {
        _config = [[WKWebViewConfiguration alloc] init];
        // 设置偏好设置
        _config.preferences = [[WKPreferences alloc] init];
        // 默认为0
        _config.preferences.minimumFontSize = 10;
        // 默认认为YES
        _config.preferences.javaScriptEnabled = YES;
        // 在iOS上默认为NO,表示不能自动通过窗口打开
        _config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        
        /**
         *  scriptMessageHandler是代理回调,JS调用name方法后,
         *  OC会调用scriptMessageHandler指定的对象
         */
        [_config.userContentController addScriptMessageHandler:self name:@"iSailor"];
    }
    return _config;
}

使用:

WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:_config];

只好重头捋一捋才发现原来在这里:

我使用的时候都是用的_config,所以不会走getter方法;
使用的时候将_config改为self.config就可以了

WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:self.config];

原因:self.config会调用类的getter方法,而如果直接用_config只是直接访问类的实例变量,而不会调用getter方法了。

上一篇 下一篇

猜你喜欢

热点阅读