懶加載——也稱(chēng)為延遲加載泊柬,即在需要的時(shí)候才加載(效率低醇蝴,占用內(nèi)存小).所謂懶加載溜哮,寫(xiě)的是其get方法.
注意:如果是懶加載的話則一定要注意先判斷是否已經(jīng)有了,如果沒(méi)有那么再去進(jìn)行實(shí)例化.
每個(gè)控件的getter方法中分別負(fù)責(zé)各自的實(shí)例化處理色解,代碼彼此之間的獨(dú)立性強(qiáng)茂嗓,松耦合.
```
?@property(nonatomic,strong)UILabel *firstlab;
?@property(nonatomic,strong)UILabel *lastlab;
?@property(nonatomic,strong)UIImageView *icon;
?@property(nonatomic,strong)UIButton *leftbtn;
@property(nonatomic,strong)NSArray *array;
@property(nonatomic ,assign)int i;
?-(void)change;
?@end
?@implementation YYViewController
?- (void)viewDidLoad
{
? ? [super viewDidLoad];
? ? ?[self change];
?}
-(void)change
?{
? ? ?[self.firstlab setText:[NSString stringWithFormat:@"%d/5",self.i+1]]; ? ? //先get再set
? ? self.icon.image=[UIImage imageNamed:self.array[self.i][@"name"]];
? ? ?self.lastlab.text=self.array[self.i][@"desc"];
? ? self.leftbtn.enabled=(self.i!=0);
? ? ?self.rightbtn.enabled=(self.i!=4);
?}
?//延遲加載
?/**1.圖片的序號(hào)標(biāo)簽*/
?-(UILabel *)firstlab
?{
//判斷是否已經(jīng)有了,若沒(méi)有科阎,則進(jìn)行實(shí)例化
? ? ?if (!_firstlab) {
? ? ? ? _firstlab=[[UILabel alloc]initWithFrame:CGRectMake(20, 10, 300, 30)];
? ? ? ? [_firstlab setTextAlignment:NSTextAlignmentCenter];
? ? ? ?[self.view addSubview:_firstlab];
? ? }
? ? return _firstlab;
}
?/**2.圖片控件的延遲加載*/
?-(UIImageView *)icon
?{
? ? //判斷是否已經(jīng)有了述吸,若沒(méi)有,則進(jìn)行實(shí)例化
? ? ?if (!_icon) {
? ? ? ? _icon=[[UIImageView alloc]initWithFrame:CGRectMake(POTOIMGX, POTOIMGY, POTOIMGW, POTOIMGH)];
? ? ? ? ?UIImage *image=[UIImage imageNamed:@"biaoqingdi"];
_icon.image=image;
[self.view addSubview:_icon];
? ? ?}
? ? ?return _icon;
?}
/**3.描述控件的延遲加載*/
-(UILabel *)lastlab
?{
//判斷是否已經(jīng)有了萧恕,若沒(méi)有刚梭,則進(jìn)行實(shí)例化
? ? ?if (!_lastlab) {
? ? ? ? ?_lastlab=[[UILabel alloc]initWithFrame:CGRectMake(20, 400, 300, 30)];
? ? ? ? ?[_lastlab setTextAlignment:NSTextAlignmentCenter];
? ? ? ? ?[self.view addSubview:_lastlab];
}
? ? ?return _lastlab;
?}
?/**4.左鍵按鈕的延遲加載*/
?-(UIButton *)leftbtn
?{
? ? ? //判斷是否已經(jīng)有了肠阱,若沒(méi)有,則進(jìn)行實(shí)例化
? ? ?if (!_leftbtn) {
? ? ? ? ?_leftbtn=[UIButton buttonWithType:UIButtonTypeCustom];
? ? ? ? ?_leftbtn.frame=CGRectMake(0, self.view.center.y, 40, 40);
? ? ? ? ?[_leftbtn setBackgroundImage:[UIImage imageNamed:@"left_normal"] forState:UIControlStateNormal];
? ? ? ? ?[_leftbtn setBackgroundImage:[UIImage imageNamed:@"left_highlighted"] forState:UIControlStateHighlighted];
? ? ? ? ?[self.view addSubview:_leftbtn];
? ? ? ? ?[_leftbtn addTarget:self action:@selector(leftclick:) forControlEvents:UIControlEventTouchUpInside];
? ? ?}
? ? return _leftbtn;
```