Lazyload 懒加载

来源:互联网 发布:汤灿到底怎么了知乎 编辑:程序博客网 时间:2024/06/03 18:15

懒加载

  1. 基本定义
    也称为延迟加载,当对象需要用到的时候再去加载。

  2. 用法
    其实就是所谓的重写对象的get方法,当系统或者开发者调用对象的get方法时,再去加载对象。

    需要注意:重写get方法时,先判断对象当前是否为空,为空的话再去实例化对象

  3. 优点

    • 不需要将创建对象的代码写到viewDidLoad,可以简化代码,增强代码的可读性
    • 对象的实例化在getter方法中,各司其职,降低耦合性
    • 当真正需要资源时,再去加载,系统的内存占用率会减小
  4. 例1

//声明一个变量@property(nonatomic,strong) UILabel *vicLabel;@implementation TestViewController-(void)viewDidLoad{    [super viewDidLoad];    [self change];}-(void)change{    // 使用self.vicLabel,其实是会先调用getter方法,因为用.property,其实就是getter方法。但是需要注意的是:在重写的getter方法里,切勿使用self.vicLabel,因为这种.的语法,会调用getter方法,这就造成了死循环。    [self.vicLabel setText:@"我是vic"];}//重写getter方法-(UILabel *)vicLabel{    // 首先判断是否已经有了,若没有,则进行实例化,这是重点,必须要先判断    if(!_vicLabel){        _vicLabel = [UILabel alloc] initWithFrame:CGRectMake(20,30,200,50)];        [_vicLabel setTextAlignment:NSTextAlignmentCenter];        [self.view addSubview:_vicLabel];    }    return _vicLabel;}

. 例2

@interface ViewController()@property (nonatomic,strong) NSArray *shopData;@end@implementation ViewController-(void)viewDidLoad{    [super viewDidLoad];    _shopData = [NSArray arrayWithContentsOfFile:[NSBundle mainBundle] pathForResource:@"shop" ofType:@"plist"]];}@end
  • 显而易见,当控制器被加载完成以后,就会加载当前的shopData,假如shopData是在某些事件被触发的时候才会被调用,没必要在控制器加载完就去获取plist文件,如果事件不触发,代表着shopData永远不会被用到,这样在viewDidLoad中加载shopData就会十分多余,并且耗用内存

懒加载代码示例

@interface ViewController()@property (nonatomic,strong) NSArray *shopData;@end@implementation ViewController-(void)viewDidLoad{    [super viewDidLoad];}-(NSArray *) shopData{    if(_shopData){        _shopData = [NSArray arrayWithContentOfFile:[NSBundle mainBundle] pathForResource:@"shop" ofType:@"plist"]];    }    return _shopData;}
  • 当需要用到shopData的时候,就会调用self.shopData,即getter方法,然后再getter方法中获取plist文件内容,然后返回使用(注意,在getter方法中切勿使用self.shopData,因为self.shopData会调用getter方法,造成死循环)
0 0
原创粉丝点击