1.懒加载基本
懒加载——也称为延迟加载,即在需要的时候才加载(效率低,占用内存小)。所谓懒加载,写的是其get方法.
注意:如果是懒加载的话则一定要注意先判断是否已经有了,如果没有那么再去进行实例化
2.使用懒加载的好处:
(1)不必将创建对象的代码全部写在viewDidLoad方法中,代码的可读性更强
(2)每个控件的getter方法中分别负责各自的实例化处理,代码彼此之间的独立性强,松耦合
3. 代码示例:
如:plist资源文件的懒加载
#import "ViewController.h"
@interface ViewController ()<UIPickerViewDataSource,UIPickerViewDelegate>
@property(nonatomic,strong) NSArray *foods;
@end
@implementation ViewController
-(NSArray *)foods{
if (!_foods) {
NSString *path = [[NSBundle mainBundle]pathForResource:@"foods.plist" ofType:nil];
_foods = [NSArray arrayWithContentsOfFile:path];
}
return _foods;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSLog(@"%@",self.foods);
}
3.1 UI控件的懒加载方法
6 @interface YYViewController ()
17
18 @property(nonatomic,strong)UILabel *firstlab;
19 @property(nonatomic,strong)UILabel *lastlab;
20 @property(nonatomic,strong)UIImageView *icon;
25 -(void)change;
26 @end
27
28
30 @implementation YYViewController
31
32 - (void)viewDidLoad
33 {
34 [super viewDidLoad];
35 [self change];
36 }
37
38 -(void)change
39 {
40 [self.firstlab setText:[NSString stringWithFormat:@"%d/5",self.i+1]];
41 //先get再set
42
43 self.icon.image=[UIImage imageNamed:self.array[self.i][@"name"]];
44 self.lastlab.text=self.array[self.i][@"desc"];
45
46 self.leftbtn.enabled=(self.i!=0);
47 self.rightbtn.enabled=(self.i!=4);
48 }
49
50 //延迟加载
51 /**1.图片的序号标签*/
52 -(UILabel *)firstlab
53 {
54 //判断是否已经有了,若没有,则进行实例化
55 if (!_firstlab) {
56 _firstlab=[[UILabel alloc]initWithFrame:CGRectMake(20, 10, 300, 30)];
57 [_firstlab setTextAlignment:NSTextAlignmentCenter];
58 [self.view addSubview:_firstlab];
59 }
60 return _firstlab;
61 }
62
63 /**2.图片控件的延迟加载*/
64 -(UIImageView *)icon
65 {
66 //判断是否已经有了,若没有,则进行实例化
67 if (!_icon) {
68 _icon=[[UIImageView alloc]initWithFrame:CGRectMake(POTOIMGX, POTOIMGY, POTOIMGW, POTOIMGH)];
69 UIImage *image=[UIImage imageNamed:@"biaoqingdi"];
70 _icon.image=image;
71 [self.view addSubview:_icon];
72 }
73 return _icon;
74 }
75
76 /**3.描述控件的延迟加载*/
77 -(UILabel *)lastlab
78 {
79 //判断是否已经有了,若没有,则进行实例化
80 if (!_lastlab) {
81 _lastlab=[[UILabel alloc]initWithFrame:CGRectMake(20, 400, 300, 30)];
82 [_lastlab setTextAlignment:NSTextAlignmentCenter];
83 [self.view addSubview:_lastlab];
84 }
85 return _lastlab;
86 }