懒加载

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值