程序员

iOS UI 懒加载

2016-05-13  本文已影响246人  阳光下慵懒的驴

懒加载——也称为延迟加载,即在需要的时候才加载(效率低,占用内存小)。所谓懒加载,写的是其getter方法。说的通俗一点,就是在开发中,当程序中需要利用的资源时。在程序启动的时候不加载资源,只有在运行当需要一些资源时,再去加载这些资源。
懒加载的核心在于:要注意先判断对象是否已经存在,如果不存在再实例化

使用懒加载的好处:

实例:

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, retain) UIButton * lazyButton;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createViews];
}
- (void)createViews{
    // 在这里一定要写"self.",而不能使用下划线"_"。因为会发生引用计数的变化
    [self.lazyButton setTitle:@"button" forState:UIControlStateNormal];
}
// button的getter延迟加载
- (UIButton *)lazyButton{
    if(_lazyButton == nil){
        self.lazyButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2 - 50, self.view.frame.size.height/2 - 20, 100, 40)];
        [self.view addSubview:_lazyButton];
    }
    [_lazyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_lazyButton setBackgroundColor:[UIColor blackColor]];
    return _lazyButton;
}
上一篇 下一篇

猜你喜欢

热点阅读