zoukankan      html  css  js  c++  java
  • 懒加载--初步理解. by:王朋

    懒加载(LazyLoad),又称为延迟加载。

    举个例子,当我们在用网易新闻App时,看着那么多的新闻,并不是所有的都是我们感兴趣的,有的时候我们只是很快的滑过,想要快速的略过不喜欢的内容,但是只要滑动经过了,图片就开始加载了,这样用户体验就不太好,而且浪费内存.这个时候,我们就可以利用lazy加载技术,当界面滑动或者滑动减速的时候,都不进行图片加载,只有当用户不再滑动并且减速效果停止的时候,才进行加载.

    懒加载的好处:

    1> 不必将创建对象的代码全部写在viewDidLoad方法中,代码的可读性更强

    2> 每个属性的getter方法中分别负责各自的实例化处理,代码彼此之间的独立性强,松耦合

    3>只有当真正需要资源时,再去加载,节省了内存资源。

    提醒1):这是苹果公司提倡的做法。其实苹果公司做的IOS系统中很多地方都用到了懒加载的方式,比如控制器的View的创建。

    提醒2):空加载的时候,一定要使用点语法,也就是咱们所说的getter方法。

    下面举个懒加载的例子:

    1> 定义控件属性,注意:属性必须是strong的,示例代码如下

    @property (nonatomic, strong) NSArray *imageList;

    2> 在属性的getter方法中实现懒加载,示例代码如下:

    // 懒加载-在需要的时候,在实例化加载到内存中
    - (NSArray *)imageList
    {
        // 只有第一次调用getter方法时,为空,此时实例化并建立数组
        if (_imageList == nil) {
            // File表示从文件的完整路径加载文件
            NSString *path = [[NSBundle mainBundle] pathForResource:@"ImageData" ofType:@"plist"];
            NSLog(@"%@", path);
            
            _imageList = [NSArray arrayWithContentsOfFile:path];
        }
        
        return _imageList;
    }

    如上面的代码,有一个_imageList属性,如果在程序的代码中,有多次访问_imageList属性,例如下面

    self.imageList ;
    
    self.imageList ;
    
    self.imageList ;

    虽然访问了3次_imageList 属性,但是当第一次访问了imageList属相,imageList数组就不为空,
    当第二次访问imageList 时  imageList != nil;程序就不会执行下面的代码

    NSString *path = [[NSBundle mainBundle] pathForResource:@"ImageData" ofType:@"plist"];
            NSLog(@"%@", path);
            
            _imageList = [NSArray arrayWithContentsOfFile:path];

    就不会再次在PList文件中加载数据了。

  • 相关阅读:
    WCF Server Console
    Restart IIS With Powershell
    RestartService (recursively)
    Copy Files
    Stopping and Starting Dependent Services
    多线程同步控制 ManualResetEvent AutoResetEvent MSDN
    DTD 简介
    Using Powershell to Copy Files to Remote Computers
    Starting and Stopping Services (IIS 6.0)
    java中的NAN和INFINITY
  • 原文地址:https://www.cnblogs.com/sixindev/p/4468719.html
Copyright © 2011-2022 走看看