iOS-懒加载

2016-08-17  本文已影响59人  如风家的秘密
原理:懒加载是当你使用某个对象时才创建,它通过在.h文件中@property定义一个实例变量(使其实例变量拥有set和get方法),并通过复写get方法实现懒加载.当需要使用时**self.实例变量**才能实现懒加载(**_实例变量没有set和get方法是不能实现加载的**)

优点:它可以使代码可读性更高,对象和对象之间的独立性更强.

一般用法:

    [self.view addSubview:label];```

懒加载:
.h文件:

//自带set和get方法
@property (nontation,strong) UILabel *titleLabel;
@property(nonatomic,strong,readonly)UIButton *searchButton;

.m文件

//复写titleLabel 的get方法


-(UILabel*)titleLabel{

if (_titleLabel == nil) {

    _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 100, 50)];      
    [self.view addSubview:_titleLabel];
}

return _titleLabel;

}


//synthesize 取属性别名,可通过_获取实例变量
@synthesize searchButton = _searchButton;

-(UIButton *)searchButton{

if (_searchButton == nil) {
     _searchButton  = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [self.view addSubview:_searchButton];
}

return _searchButton;

}


运行效果:

![懒加载显示label和button](https://img.haomeiwen.com/i2471265/0629cf37e937e1c4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
上一篇 下一篇

猜你喜欢

热点阅读