码迷,mamicode.com
首页 > 移动开发 > 详细

IOS 懒加载模式

时间:2014-12-21 23:35:26      阅读:287      评论:0      收藏:0      [点我收藏+]

标签:

iOS开发—懒加载

1.懒加载——也称为延迟加载,即在需要的时候才加载(效率低,占用内存小)。所谓懒加载,写的是其get方法.

注意:如果是懒加载的话则一定要注意先判断是否已经有了,如果没有那么再去进行alloc init

2.我们知道iOS设备的内存有限,如果在程序在启动后就一次性加载将来会用到的所有资源,那么就有可能会耗尽iOS设备的内存。这些资源例如大量数据,图片,音频等等

下面举个例子:

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

    @property (nonatomic, strong) UIImageView *icon;

    @property (nonatomic, strong) UIButton *nextBtn;

    @property (nonatomic, strong) NSArray *imageList;

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

// 懒加载-在需要的时候,再实例化加载到内存

/***图片控件的延迟加载 ***/

-(UIImageView *)icon

{

    //判断是否已经有了,若没有,则进行实例化

    if (!_icon) {

        _icon=[[UIImageView alloc]initWithFrame:CGRectMake(x, y, w, h)];

        UIImage *image=[UIImage imageNamed:@"icon"];

        _icon.image=image;

        [self.view addSubview:_icon];

    }

    return _icon;

}

/***按钮的延迟加载 ***/

-(UIButton *)nextbtn

{

    //判断是否已经有了,若没有,则进行实例化

    if (!_nextbtn) {

        _nextbtn=[UIButton buttonWithType:UIButtonTypeCustom];

        _nextbtn.frame=CGRectMake(0, self.view.center.y, 40, 40);

        [_nextbtn setBackgroundImage:[UIImage imageNamed:@"normal"] forState:UIControlStateNormal];

        [_nextbtn setBackgroundImage:[UIImage imageNamed:@"highlighted"] forState:UIControlStateHighlighted];

        [self.view addSubview:_nextbtn];

        [_nextbtn addTarget:self action:@selector(nextClick:) forControlEvents:UIControlEventTouchUpInside];

    }

    return _nextbtn;

}

/*** array的get方法 ***/

- (NSArray *)imageList{

    // 只有第一次调用getter方法时,为空,此时实例化并建立数组

    if (_imageList == nil) {

        // File表示从文件的完整路径加载文件

        NSString *path = [[NSBundle mainBundle] pathForResource:@"ImageData" ofType:@"plist"];

        _imageList = [NSArray arrayWithContentsOfFile:path];

     }

    return _imageList;

}

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

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

虽然访问了3次_imageList 属性,但是当第一次访问了imageList属相,imageList数组就不为空,
当第二次访问imageList 时  imageList != nil,就不会再次在PList文件中加载数据了。

3. 使用懒加载的好处:

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

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

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

IOS 懒加载模式

标签:

原文地址:http://www.cnblogs.com/chengfang/p/4177198.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!