iOS uses lazy loading

Lazy loading of nature

Lazy loading, also called lazy loading, that is, before going to load the first time needed for getter method is to rewrite an instance of nature.

The use of lazy loading

Lazy loading is relatively simple to use, give chestnut
#import "ViewController.h"

	@interface ViewController ()
	@property (nonatomic, strong) UILabel *label;
	@end
	
	@implementation ViewController
	
	- (void)viewDidLoad {
	    [super viewDidLoad];
	    [self label];
	}
	
	- (UILabel *)label {
	    if (!_label) {
	        _label = [[UILabel alloc] init];
	        _label.frame = CGRectMake(64, 64, 300, 50);
	        _label.backgroundColor = [UIColor cyanColor];
	        _label.text = @"懒加载就是当需要的时候才去加载";
	        [self.view addSubview:_label];
	    }
	    return _label;
	}
	
	@end

## 懒加载的注意点

使用懒加载时,必须注意getter方法嵌套,从而造成死循环,导致程序crash!, 比如,我们写成这样:

- (UILabel *)label {
    // 注意这里会造成程序奔溃,getter方法自身嵌套循环,永无休止
    if (!self.label) {
        _label = [[UILabel alloc] init];
        _label.frame = CGRectMake(64, 64, 300, 50);
        _label.backgroundColor = [UIColor cyanColor];
        _label.text = @"懒加载就是当需要的时候才去加载";
    }
    return _label;
}
又或者写成

- (UILabel *)label {
    if (!_label) {
        _label = [[UILabel alloc] init];
        _label.frame = CGRectMake(64, 64, 300, 50);
        _label.backgroundColor = [UIColor cyanColor];
        _label.text = @"懒加载就是当需要的时候才去加载";
    }
    // 注意这里会造成程序奔溃,getter方法自身嵌套循环,永无休止
    return self.label;
}

Of course, there is another as long as you remember, casually you how to write, and foolproof method will never result in an infinite loop, that is not lazy loading method names and instance variables of the same name inside lazy loading, so Xcode you can accurately identify your call attribute or lazy loading methods, such as:

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) UILabel *label;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self lazyMethod];
}

- (UILabel *)lazyMethod {
    if (!self.label) {
        _label = [[UILabel alloc] init];
        _label.frame = CGRectMake(64, 64, 300, 50);
        _label.backgroundColor = [UIColor cyanColor];
        _label.text = @"懒加载就是当需要的时候才去加载";
        [self.view addSubview:_label];
    }
    return self.label;
}

@end

This is a good way of writing lazy loading, clear, and safe and reliable.

Note II: the issue of the layout

If Masonry layout of the page, then on the code frame must not be placed get overridden methods, the error will be reported otherwise can not find the parent view, should be placed behind addSubview
error:

The correct wording of the code:

#import "ViewController.h"
#import "Masonry.h"

@interface ViewController ()

@property (nonatomic, strong) UILabel * title_lab;

@end

@implementation ViewController

-(UILabel *)title_lab
{
    if (!_title_lab) {
        self.title_lab = [[UILabel alloc]init];
        self.title_lab.textAlignment = NSTextAlignmentCenter;
        self.title_lab.textColor = [UIColor blueColor];
        self.title_lab.text = @"lazyLoad";
        [self.title_lab sizeToFit];
    }
    
    return _title_lab;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    //只是加载到预想加载的view上,不在初始化方法里为其alloc/init。只是一个指针,不会占内存
    [self.view addSubview:self.title_lab];
    
    //Masonry布局设置必须写在addSubview:之后
    [self.title_lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(100, 40));
    }];
    
}

@end

Why use lazy loading?

There are many online article discusses the use of lazy loading point of view, we look at some of those common advantages

First, lazy loading does not have to write on the inside viewDidLoad method, getter methods for each attribute are responsible for each instantiation process, and therefore more readable, more independence
I personally feel that this is only relative, readable strong also depends on how you write, how to write, if we need to create a 100 view, if this 100 view all use lazy loading, then what advantage? So it's more readable? More independence it? We all know that using lazy loading, lazy loading each create a code amount will be more than 3-4 lines, if we create 100 views, then it is more out of the 300-400 line? Therefore readability becomes not so strong, on the contrary, if we directly use the technology to create separate component views, and then call in the viewDidLoad, so instead of clarity, readability is really strong. Of course, if only in the case of several views, that lazy loading does seem clearer, more readable, then the problem is that if just a few simple view, why use lazy loading, what advantage?

This problem Summary: lazy loading readable, strong independence is not absolute, even minimal, and I personally think it has much advantage or advantages.
Second, lazy loading can prevent instances is nil
this advantage may be there, but only relative, usually under normal circumstances, as a qualified programmer (and maybe I failed, because I did not once, because security code inspection and Ben collapse too), will do the variables used in security checks, array bounds as to prevent the same, resulting in the program Ben collapse!

Of course, lazy loading, as has been done independently of the security check, so do not need to go again tedious and repetitive to check whether to nil, indeed it would be a good choice for subsequent use, however, this is not to talk too on how much advantage, but relatively speaking, did a similar check of the global approach it.

This is regarded as a relative advantage lazy loading, but not absolute.
Third, lazy loading to save memory resources
of this to some extent is justified if and only when we need to load only called lazy loading, for example, when the network requests, we can not know whether the request fails, is because the network failure, or because the data request is empty? No network, we will show a network error page, and this network error page that we can use lazy loading, because under normal circumstances, the network is good, is not required to load the network error page exists, but also to prevent in case, for example, when we use an app, and suddenly entered the elevator or basement, are likely to lead to network failure; if the network under good circumstances, perhaps we request down data is empty, it can be at this time load a empty page that you can use lazy loading.

Of course, the beginning of the examples in this article is not necessary to use lazy loading, because there is no need, lazy loading according to the time, when resources needed only to use lazy loading, so as to save memory. Let's say again, we need to load data model network request down, but the page is loaded, it then we can also use lazy loading, because the user may upload the LAC just read a few pages is not loaded, or some use cached data and many more.

Lazy loading properly use can indeed save memory resources, there is a certain degree of performance optimization, which is more convinced of the advantages I have, in addition, I personally feel that a stage can save time, that is, before calling lazy loading, if has not been back to using lazy loading, then we can save some of that time to load lazy loaded.
When using lazy loading?

Under normal circumstances, without the use of lazy loading, lazy loading may not be able to enhance readability, independence, but let readability abuse counterproductive. In short, that is, logically, that now need to load, and may be loaded in the back of a period of time, you can consider lazy loading.

to sum up

Advantage of lazy loading

In contrast, if the code is not a lot of volume, readability slightly stronger

Relatively speaking, prevent to nil, reducing worries subsequent use of the security check

Properly used, can save memory resources

To some extent, saving time within a certain period

Used properly, optimize performance, improve the user experience

Note: The above are only so-called advantages, relatively speaking, is not absolute, the key is to look at how you use! So lazy loading good and bad, who is still in use.
Shortcoming lazy loading

Use overabundance, lead to less readable

Use shall not be treated, it may cause an infinite loop, resulting in crash

Increase the amount of code (each additional lazy loaded, the code will average more than 3-4 lines)

Note: The above so-called shortcomings only relatively speaking, vary, after all, to open it, in addition to lazy load the technical point outside of any technical errors or logic, the final output is a bug .

Published 34 original articles · won praise 4 · Views 731

Guess you like

Origin blog.csdn.net/weixin_44824650/article/details/102645465