Lazy loading is also called delayed loading. To put it bluntly, it is to say that in development, when the resources need to be used in the program. Resources are not loaded when the program starts. These resources are loaded only when some resources are required for running.
We know that the memory of iOS devices is limited. If you load all the resources that will be used in the future at one time after the program starts, the memory of iOS devices may be exhausted. These resources, such as large amounts of data, images, audios, etc.
The following is an example:
1> define control properties. Note: The properties must be strong. The sample code is as follows:
@property (nonatomic, strong) NSArray *imageList;
2> implement lazy loading in the getter method of the attribute. The sample code is as follows:
// Lazy loading-when required, it is instantiated and loaded into the memory-(NSArray *) imageList {// It is null only when the getter method is called for the first time, in this case, instantiate and create an array if (_ imageList = nil) {// File to load the File NSString * path = [[NSBundle mainBundle] pathForResource: @ "ImageData" ofType: @ "plist"]; NSLog (@ "% @", path); _ imageList = [NSArray arrayWithContentsOfFile: path];} return _ imageList ;}
The code above has a _ imageList attribute. If the program code has multiple accesses to the _ imageList attribute, for example, the following
self.imageList ;self.imageList ;self.imageList ;
Although the _ imageList attribute is accessed three times, the imageList array is not empty when imageList is accessed for the first time,
ImageList! = Nil; the program will not execute the following code
NSString *path = [[NSBundle mainBundle] pathForResource:@"ImageData" ofType:@"plist"]; NSLog(@"%@", path); _imageList = [NSArray arrayWithContentsOfFile:path];
It will not load data in the PList file again.
Benefits of lazy loading:
1> do not write all the code for creating an object in the viewDidLoad method, making the code more readable.
2> the getter method of each attribute is responsible for instantiating each other. The code is highly independent and loosely coupled.
3> only when resources are actually needed can they be loaded, saving memory resources.
Note: This is what Apple advocates. In fact, many IOS systems made by Apple use lazy loading methods, such as creating a controller View.
I will discuss it later in my blog. Welcome to the discussion.