您的位置:首页 > 其它

懒加载

2016-04-20 17:51 204 查看
1.懒加载基本

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

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

2.使用懒加载的好处

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

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

3.代码示例

#import "ViewController.h"

@interface ViewController ()

@property(nonatomic,strong) UILabel *firstLabel;

@property(nonatomic,strong) UILabel *secondLable;

@property(nonatomic,strong) UIButton *leftButton;

@property(nonatomic,strong) NSMutableArray *array;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.leftButton.enabled = YES;
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

/**
*  延迟加载
**/
- (UILabel*)firstLabel{
//判断是否已经有了,若没有,则进行实例化
if (!_firstLabel) {
_firstLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 300, 30)];
_firstLabel.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:_firstLabel];
}
return _firstLabel;
}

- (UILabel*)secondLable{
//判断是否已经有了,若没有,则进行实例化
if (!_secondLable) {
_secondLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, 300, 30)];
_secondLable.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:_secondLable];
}
return _secondLable;
}

- (UIButton*)leftButton{
//判断是否已经有了,若没有,则进行实例化
if (!_leftButton) {
_leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0,
120,
[UIScreen mainScreen].bounds.size.width,
30)];
[_leftButton setTitle:@"点击" forState:UIControlStateNormal];
[_leftButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[_leftButton addTarget:self
action:@selector(leftButtonClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_leftButton];
}
return _leftButton;
}

- (NSMutableArray*)array{
//判断是否已经有了,若没有,则进行实例化
if (!_array) {
_array = [[NSMutableArray alloc] initWithObjects:@"ios",@"懒加载",@"代码",@"示例", nil];
}
return _array;
}

#pragma mark -按钮事件
- (void)leftButtonClick{
self.firstLabel.text = [NSString stringWithFormat:@"%@%@",self.array[0],self.array[1]];
self.secondLable.text = [NSString stringWithFormat:@"%@%@",self.array[2],self.array[3]];
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: