iOS 懒加载模式

来源:互联网 发布:哪个银行的淘宝卡最好 编辑:程序博客网 时间:2024/04/28 05:44

1.概念

          懒加载模式又叫懒人模式或者延迟加载,只有在需要的时候才进行加载,可用来加载控件、属性。懒加载模式的实质就是一个特殊的getter方法,特殊在在getter方法的内部包含一段用于初始化创建对象的代码逻辑,但该逻辑只会执行一次。


2.优点

          因为懒加载代码逻辑只执行一次,而且是在需要的时候才会执行,不需要的时候就不执行,就提高了代码的效率,节约了系统所占用内存的资源;

  使用懒加载模式可以将控件的初始化都放在getter方法中,这样可以降低viewDidLoad方法的复杂度,使得代码更加简洁,降低的代码的耦合度


3.示例代码

#import "ViewController.h"@interface ViewController () <UITableViewDataSource, UITableViewDelegate>@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];        // 懒加载,调用当前类的某个属性的getter方法    [self.view addSubview:self.tableView];}#pragma mark -#pragma mark - 懒加载- (UITableView*) tableView {    // 需要的时候才执行,只执行一次    // 必须先判断该变量没有初始化,才进行初始化    if (!_tableView) {        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];        _tableView.delegate = self;        _tableView.dataSource = self;    }        return _tableView;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {    return 1;}- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    static NSString *cellIdentifier = @"cellIdentifier";    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];    if (cell == nil) {        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];    }        cell.textLabel.text = @"item...";        return cell;}@end

4.代码分析

        从以上代码示例可以看出,如果使用懒加载,将控件的初始化都放到getter方法中,viewDidLoad方法的代码量将会很少,看起来很简洁

0 0
原创粉丝点击