OC lazy loading method

Get into the habit of writing together! This is the first day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

When it comes to lazy loading, maybe 99% of the students who are engaged in iOS development will use it. As we all know, lazy loading is to load it when it is used. Usually, we use it as an attribute and implement it through self.xx. So have you heard of lazy loading of OC methods? Have you used it? The following is to implement lazy loading of methods through runtime, and play.

First create a Person class, nothing in the .h file needs to be written

image.png

Import the header file in ViewController and start playing

image.png

In the viewdidload method, initialize the person and call the eat method of the person. At this time, you can see the xcode compilation warning eat method. If we run the code now, it will crash, because this method cannot be found, find Person.m

image.png

Objective C provides a facility called dynamic method resolution that allows us to dynamically provide implementations for a selector at runtime. We only need to implement the +resolveInstanceMethod: or +resolveClassMethod: method, and provide the implementation for the specified selector in it (add by calling the runtime function class_addMethod). Both of these methods are class methods in NSObject, and their prototypes are:

  • (BOOL)resolveClassMethod:(SEL)name; 

 + (BOOL)resolveInstanceMethod:(SEL)name;

Simply put, when a method that is not implemented in this class is called, it will enter the method.

The parameter name is the selector that needs to be dynamically resolved; the return value document says that it indicates whether the dynamic resolution is successful or not. But in the above example ( without involving message forwarding ), if you provide an implementation for the specified selector within the function, whether it returns YES or NO, the compilation and operation are correct; but if it is not really within the function Provide an implementation for the selector, no matter whether it returns YES or NO, the operation will crash. The reason is very simple. The selector does not have a corresponding implementation, and it does not implement message forwarding.

resolveInstanceMethod is to resolve object methods,

And resolveClassMethod is to resolve the class method.

First simply run the code and print the SEL to see what the method is

image.png

It can be clearly seen that the eat was called before, and then the dynamic method resolution method is used to modify the above code:

image.png

Parse:

image.png

Guess you like

Origin juejin.im/post/7082381186676293662