下面举个例子:html
1> 定义控件属性,注意:属性必须是strong的,示例代码以下:
数组
@property (nonatomic, strong) NSArray *imageList;
2> 在属性的getter方法中实现懒加载,示例代码以下:atom
// 懒加载-在须要的时候,在实例化加载到内存中 - (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属性,例以下面spa
self.imageList ; self.imageList ; self.imageList ;
虽然访问了3次_imageList 属性,可是当第一次访问了imageList属相,imageList数组就不为空,
当第二次访问imageList 时 imageList != nil;程序就不会执行下面的代码xml
NSString *path = [[NSBundle mainBundle] pathForResource:@"ImageData" ofType:@"plist"]; NSLog(@"%@", path); _imageList = [NSArray arrayWithContentsOfFile:path];
就不会再次在PList文件中加载数据了。htm
懒加载的好处:
1> 没必要将建立对象的代码所有写在viewDidLoad方法中,代码的可读性更强
2> 每一个属性的getter方法中分别负责各自的实例化处理,代码彼此之间的独立性强,松耦合 对象
3>只有当真正须要资源时,再去加载,节省了内存资源。 图片