IOS 懒加载模式

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) 只有当真正需要资源时,再去加载,节省了内存资源。

转载于:https://www.cnblogs.com/chengfang/p/4177198.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值