1.懒加载的概念
懒加载——也称为延迟加载,即在需要的时候才加载(效率低,占用内存小)。所谓懒加载,写的是其get方法.
注意:如果是懒加载的话则一定要注意先判断是否已经有了,如果没有那么再去进行实例化
2.使用懒加载的好处:
(1)不必将创建对象的代码全部写在viewDidLoad方法中,代码的可读性更强
(2)每个控件的getter方法中分别负责各自的实例化处理,代码彼此之间的独立性强,松耦合
(3)对系统的内存占用率会减小
3.下面举个例子:
1> 定义控件属性,注意:属性必须是strong的,示例代码如下:
@property (nonatomic, strong) NSArray *imageList;
2> 在属性的getter方法中实现懒加载,示例代码如下:
// 懒加载-在需要的时候,在实例化加载到内存中 - (NSArray *)imageList { // 只有第一次调用getter方法时,为空,此时实例化并建立数组 if (_imageList == nil) { // File表示从文件的完整路径加载文件 NSString *path = [[NSBundle mainBundle] pathForResource:@"ImageData" ofType:@"plist"]; NSLog(@"%@", path); _imageList = [NSArray arrayWithContentsOfFile:path]; } return _imageList; }
如上面的代码,有一个_imageList属性,如果在程序的代码中,有多次访问_imageList属性,例如下面
self.imageList ; self.imageList ; self.imageList ;
虽然访问了3次_imageList 属性,但是当第一次访问了imageList属相,imageList数组就不为空,
当第二次访问imageList 时 imageList != nil;程序就不会执行下面的代码
NSString *path = [[NSBundle mainBundle] pathForResource:@"ImageData" ofType:@"plist"]; NSLog(@"%@", path); _imageList = [NSArray arrayWithContentsOfFile:path];
就不会再次在PList文件中加载数据了。