懶加載——也稱(chēng)為延遲加載,即在需要的時(shí)候才加載(效率低又谋,占用內(nèi)存衅捶臁)。所謂懶加載彰亥,寫(xiě)的是其getter方法咧七。說(shuō)的通俗一點(diǎn),就是在開(kāi)發(fā)中剩愧,當(dāng)程序中需要利用的資源時(shí)猪叙。在程序啟動(dòng)的時(shí)候不加載資源,只有在運(yùn)行當(dāng)需要一些資源時(shí),再去加載這些資源穴翩。
懶加載的核心在于:要注意先判斷對(duì)象是否已經(jīng)存在犬第,如果不存在再實(shí)例化
使用懶加載的好處:
- 不必將創(chuàng)建對(duì)象的代碼全部寫(xiě)在viewDidLoad方法中,代碼的可讀性更強(qiáng)
- 每個(gè)控件的getter方法中分別負(fù)責(zé)各自的實(shí)例化處理芒帕,代碼彼此之間的獨(dú)立性強(qiáng)歉嗓,松耦合
- 只有當(dāng)真正需要資源時(shí),再去加載背蟆,節(jié)省了內(nèi)存資源鉴分。
實(shí)例:
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, retain) UIButton * lazyButton;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self createViews];
}
- (void)createViews{
// 在這里一定要寫(xiě)"self.",而不能使用下劃線"_"带膀。因?yàn)闀?huì)發(fā)生引用計(jì)數(shù)的變化
[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;
}