iOS开发懒加载

基本介绍

使用懒加载的好处:

  1. 不必将创建对象的代码全部写在viewDidLoad方法中,代码的可读性更强
  2. 每个控件的getter方法中分别负责各自的实例化处理,代码彼此之间的独立性强,松耦合
  3. 只有当真正需要资源时,再去加载,节省了内存资源。

正常加载代码示例

@interface ViewController ()
@property (nonatomic, strong) NSArray *shopData;
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    _shopData = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"shop" ofType:@"plist"]];
}
@end

使用懒加载代码示例

- (void)viewDidLoad {
    [super viewDidLoad];
}
- (NSArray *)shopData
{
    if (!_shopData) {
        _shopData = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"shop" ofType:@"plist"]];
    }
    return _shopData;
}
@end