1, RunTime Introduction:
Runtime's work in OC: The design pattern of the OC language determines that the program can be postponed from compile and link to runtime whenever possible. Whenever possible, OC always uses a dynamic approach to solve the problem. This means that the OC language requires not only a compiler, but also a runtime system to execute the compiled code. The runtime system here plays a role similar to the OC language operating system, and OC works based on that system.
2. RunTime Common scene:
1. Assign values to properties:
For example, I first create a Student object, which defines two properties: name, age, see
This time running the printed name is "John Doe".
2. Dynamic Association properties:
Dynamic Association is generally given to the OC native class add Class (category) and to add attributes to the class, the use of dynamic Association, we know: The class is not directly add attributes (why not, can Baidu, where the focus on dynamic Association, do not do too much explanation), The purpose can only be achieved by dynamic association operations, and the following examples are given:
For example, to add UILabel to the head, the header file is as follows:
The. m implementation file is as follows:
Then the controller is cited #import "uilabel+name.h" header file, so that the controller to write the following code:
This time, you can print it out: "123456". The two methods implemented in UILABEL+NAME.M are the getter and setter methods of dynamic association properties, which must be implemented or run directly to crash.
3, method swizzling Runtime dynamic Exchange methods:
The code examples are as follows:
This time to call the Eat method, will print "222222222222222222", and call the Run method will print "111111111111111" out, it is amazing, this time has been implemented in runtime dynamic Exchange method.
3. Summary:
Here are just a few of the common scenarios, of course, there are: like OC message forwarding mechanism is also based on RunTime to achieve, the specific scenario also requires the reader to apply, RunTime for beginners IOS, may not be common, but with the depth of study, this mechanism must be understood, And some complex application scenarios are often used.
Some of the scenarios used by IOS RunTime