懒加载数据

懒加载数据

懒加载介绍

懒加载也称为延迟加载,即在需要的时候,才加载(效率低,内存占用小)。所谓的懒加载,就是在相应的对象的get方法中对数据进行初始化。

这里需要注意:1.懒加载需要先判断数据是否已经有了,如果有了就不需要进行实例化了。

2.在get方法中,对象需要用_xxx方式来表示,否则会造成函数循环调用。

3.在外部需要使用self.xxx方法来调用对象才可以完成数据的get方法的调用,使用_xxx调用对象是不可以触发get方法的。

使用懒加载的好处:

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

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


//
//  ViewController.m
//  数据懒加载
//
//  Created by xxx on 15/3/23.
//  Copyright (c) 2015年 Apress. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) UILabel *lable;
@property (nonatomic, strong) UIButton *button;
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self.view addSubview:self.button];
    [self.view addSubview:self.lable];
    [self.view addSubview:self.imageView];
}

#pragma mark 懒加载
-(UILabel*) lable{
    if (_lable == nil) {
        _lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 320, 30)];
        [_lable setText:@"你好,我是戴益达"];
        [_lable setBackgroundColor:[UIColor redColor]];
    }
    return _lable;
}

-(UIButton *) button{
    if (_button == nil) {
        _button = [[UIButton alloc] initWithFrame:CGRectMake(0, 50, 100, 100)];
        [_button setTitle:@"点击按钮" forState:UIControlStateNormal];
        [_button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _button;
}

-(UIImage *) image{
    if (_image == nil) {
        _image = [UIImage imageNamed:@"picture"];
    }
    return _image;
}

-(UIImageView *) imageView{
    if (_imageView == nil) {
        _imageView = [[UIImageView alloc] initWithImage:self.image];
        [_imageView setFrame:CGRectMake(0, 200, 100, 100)];
        CGSize size = [UIScreen mainScreen].bounds.size;
        [_imageView setCenter:CGPointMake(size.width/2, size.height/2)];
    }
    return _imageView;
}

#pragma mark detail method
-(void)click:(UIButton *)Button{
    NSLog(@"已经点击按钮");
}
@end




原文地址:https://www.cnblogs.com/AbeDay/p/5026944.html