iOS UI 懒加载

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

使用懒加载的好处:

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

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

(3)只有当真正需要资源时,再去加载,节省了内存资源。

实例:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值