【iOS】lazy loading


foreword

iOS lazy loading (Lazy Loading) is a lazy loading technology that allows objects to be initialized or perform certain operations when needed, rather than immediately when the object is created. Lazy loading is mainly used to optimize the performance and memory usage of the application, especially for those operations that are time-consuming or resource-intensive.

In iOS development, lazy loading is usually used in the following scenarios:
Image loading: When loading images, you can use lazy loading to delay loading images to avoid excessive memory pressure caused by loading too many images at one time. When the image needs to be displayed, the image is loaded and displayed.
Subviews of a view controller: In a view controller, some subviews may only need to be shown under certain conditions, not every time the view controller loads. At this time, lazy loading can be used to delay loading of these subviews, thereby improving the loading performance of the view controller.
Data loading: In some scenarios where data needs to be obtained from the network or database, lazy loading can be used to request data only when needed, and cache the data to avoid repeated requests for the same data.


1. The meaning of lazy loading

When we open a program, it often takes time to wait for it to load. If the one-time loading time is too long, the user will inevitably be upset, and lazy loading will emerge as the times require.

Using lazy loading allows our program to load the content it mainly needs, and then load the content that has not been loaded when the user needs other content . A very obvious example is that when we use the app to view pictures, the pictures are not loaded at the beginning, and we need to wait for it to load for a while. At the same time, if all content is loaded at once, it will also cause a lot of waste to our mobile phone traffic


Second, the principle of lazy loading

The principle of lazy loading can be simply described as the following steps:

Create property: Declare a property in the object's interface and create an instance variable in the private member variable to hold the property.
Override Getter Method: Override the property's getter method in the implementation file. In the getter method, first check whether the private member variable has been initialized, if not, initialize it.
Lazy loading initialization: Lazy loading initialization is performed in the getter method. According to specific needs, you can create objects, load resources, make network requests, etc. here.
Return instance: returns the initialized object or resource to the caller.

We know from the principle that lazy loading is realized around the setter and getter methods.Here we must recall a knowledge we have learned before: the difference between using direct access member variables and indirect access member variables

  • Direct access to instance variables (_):
    Use _ to directly access the instance variables of the object, skipping the getter and setter methods of the property. This means that if some special logic is implemented in the getter method, using _ direct access may bypass this logic. Therefore, it is recommended to use _ inside the object and getter and setter methods outside.

  • Indirect access to instance variable (self):
    Use self to call the property's getter and setter methods. The advantage of this is that logic processing can be added to the getter and setter methods, such as lazy loading when getting attributes, or data validation when setting attributes. At the same time, accessing attributes through self can also prevent circular references, because self will be weakly referenced under ARC, and direct access to instance variables will not generate weak references.


Because our lazy loading is actually implemented by rewriting our getter method, we more often use direct access to instance variables to achieve lazy loading .Because using getter methods in lazy loading is likely to cause circular references, because lazy loading itself is a getter method, so we give the steps of lazy loading:

  1. Create a property in the .h file
@property(nonatomic, strong)UILabel *t;
  1. override getter method
- (UILabel *)t {
    
    
    if (!_t) {
    
    //不能使用self.t,会造成getter方法的循环引用
        _t = [[UILabel alloc] init];
        //一些初始化操作
    }
    return _t;//不能使用self.t,会造成getter方法的循环引用
}
  1. Access the users attribute via self.users or [self users] to trigger lazy loading
// 加载网络数据
self.t = [LXBUsers objectArrayWithKeyValuesArray:responseObject[@"t"]];
[self t];

3. Advantages and disadvantages of lazy loading

advantage:

Resource saving: Lazy loading can avoid loading data or performing operations immediately when the object is initialized, and only load or execute when it is really needed, thus saving unnecessary resource consumption and improving performance and efficiency.
Lazy loading: Lazy loading can delay the loading or operation of data until it is needed, which can improve the startup speed and response speed of the application.
Reduce memory usage: In lazy loading, object data or resources are only loaded into memory when needed, avoiding the situation where a large amount of data is loaded at one time and the memory usage is too high.

shortcoming:

Implementation complexity: increase the readability of the code and increase the amount of code. Interface
freeze caused by lazy loading: If a lot of lazy loading is used on the interface, it may cause a short interface freeze when the relevant data is accessed for the first time, because the loading operation needs to be performed at this time.
Additional resource consumption: Although lazy loading avoids loading all data at the beginning, it still needs to be loaded when needed, which will bring certain resource consumption, especially when the network requests or reads a large amount of data.

Guess you like

Origin blog.csdn.net/weixin_72437555/article/details/131881747