IOS tips: the use of lazy loading of attributes

Lazy loading refers to the method of instantiating and creating objects when they are in use. The use of lazy loading can reduce memory usage and is a common trick in ios development.

1. The principle of lazy loading

Lazy loading is actually used on the basis of the getter method. When we use . to access the internal property, it is actually the getter method of the called object. Therefore, in the implementation file, we only need to rewrite the getter method of calling the property object, and in the getter method Complete the instantiation of the object and make basic settings, so that it will judge whether it exists when it is accessed for the first time, and if it does not exist, it will be created and returned.

It is worth noting that you cannot use self. to call the object inside the getter method, because the point call is actually the getter method called, which will cause a circular call and an infinite loop.

2. The use of lazy loading

<span style="font-size:18px;">#import "ViewController.h"

@interface ViewController ()<UIWebViewDelegate>

@property(nonatomic,strong)UIWebView *webView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSURL *fileUrl = [[NSBundle mainBundle]URLForResource:@"main" withExtension:@"html"];
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:fileUrl];
    
    //It is loaded when the webview is called here
    [self.webView loadRequest:request];
    
}

//lazyload
-(UIWebView *)webView{
    / / Determine whether it has been created, if it has been created, it will return directly, if it has not been created, it will be instantiated
    if (!_webView) {
        // instantiate the object
        _webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
        //Assign some properties of the object
        _webView.delegate = self;
        _webView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_webView];
    }
    //return object
    return _webView;
}


@end
</span>

3. Advantages

Using lazy loading can say that the creation of objects can be managed separately, which is more convenient to maintain

Save the consumption of memory resources, and only create objects when they are really needed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325444424&siteId=291194637