In-depth analysis of the Runtime mechanism in iOS development, and development of the runtime mechanism in ios

Source: Internet
Author: User

In-depth analysis of the Runtime mechanism in iOS development, and development of the runtime mechanism in ios

This article mainly describes the runtime mechanism involved in OC development:

Running work:

Runtime work in OC: The design mode of OC language determines that the program should be postponed from compilation and linking to runtime as much as possible. As long as possible, OC always uses dynamic methods to solve the problem. This means that the OC language requires not only a compiler, but also a runtime system to execute compiled code. Here, the runtime system plays a role similar to the OC language operating system, where the OC works.

 

Simple application during runtime:

The system reference database for OC 2.0 runtime describes the data structure and function interfaces of the OC runtime database. The program can use these interfaces to interact with the OC runtime system. For example, add a class or method, or obtain the definition list of all classes.

 

Two runtime versions:

The OC runtime system has two versions. Earlier versions are mainly used in OC1.0. The current version is used in OC2.0. in earlier versions, if the layout of instance variables in the class is changed, you must re-compile all subclasses of the class. In the current version, if you change the layout of instance variables in the class, you do not need to re-compile any subclass of the class. Early versions are generally used for 32-bit programs in the Max OS X system. In addition, they can be regarded as all current versions.

 

 

Interaction path:

1. Source Code through OC:

When compiling OC classes and methods, the compiler automatically creates some data structures and functions for implementing the dynamic features of statements. The main function of the runtime system is to send messages according to the expressions in the source code.

 

2. NSObject-like methods in the Foundation framework:

Most classes in the Cocoa program are subclasses of the NSObject class. Therefore, most of them inherit NSObject class methods and therefore inherit NSObject class behaviors. However, in some cases, the NSObject class only defines the template for completing a specific task, but does not provide all the required code. Some NSObject methods simply obtain information from the runtime system, this allows the object to perform a certain degree of self-check. For example, if the class returns the class of the object: isKindOfClass: And isMemberOfClass: Check whether the object is in the specified class inheritance system; respondsToSelector: Check whether the object can specify the message; conformsToProtocol: check whether the object implements the method of the specified Protocol Class; methodForSelector: returns the address of the specified method implementation.

3. directly call the function of the runtime system:

The runtime system is a dynamic library of public interfaces. It consists of a set of data structures and functions. The headers of these data structures and functions are included in/usr/include/objc. These functions support the same functions as OC with pure C functions. Some functions constitute the basis of NSObject methods. These functions make it possible to access runtime system interfaces and provide development tools. Although they are not necessary in the OC program in most cases, sometimes some functions are very useful for programs such as OC.

 

Message Mechanism during running:

1. Obtain the method address:

The only way to avoid dynamic binding is to get the method address and call it directly like a function call. When a method is called for many times, and you want to save the overhead of sending messages for each method call, it is very effective to use the method address to call the method.

Using methodForSelector: Method in the NSObject class, you can obtain a pointer to the method implementation, and you can use this pointer to directly call the method implementation. MethodForSelector: The returned pointer and the assigned variable type must be exactly the same, including the parameter type and Return Value Type of the method in the scope of Type Recognition.

When a specified message is repeatedly sent many times, avoiding dynamic binding reduces the overhead of most messages.

 

2. objc_msgSend Function

In OC, messages are bound to methods only when they are running. The Compiler converts a message expression into a call to the message function objc_msgSend. This function has two main parameters: the method name corresponding to the message receiver and the message (that is, the method selection ).

Objc_msgSend (receiver er, selector), and receive any number of parameters in the message: objc_msgSend (receiver er, selector, arg1, arg2 ,...)

This message function does everything required for dynamic binding; find the corresponding method implementation --> pass the message receiver object and parameters to the method implementation --> return the return value of the method implementation as the return value of the function.

When an object receives a message, the message function first finds the method table of the class corresponding to the object based on the isa pointer of the object, and finds the Method Selection Method for the message from the table, if not, objc_msSend will find the NSObject class from the parent class. Once the selection is found, objc_msgSend calls with the message recipient object as the parameter and calls the method implementation corresponding to the selection. This is how to select method implementation in the runtime system. In object-oriented programming, it is generally called the process of dynamic binding of methods and messages.

To speed up message processing, the runtime system usually puts the used method selection and method Implementation addresses into the cache. Each class has an independent cache, including both the inherited methods and the methods defined in the class. The message function first checks the cache of the class corresponding to the Message Receiver object (theoretically, if a method is used once, it is likely to be used again ). If the required method is selected in the cache, the message is only a little slower than the function call. If the program runs for a long enough time, almost every message can find the method implementation in the cache. When the program runs, the cache will also increase with the increase of new messages.

 

3. Use hidden Parameters

When objc_msgSend finds the implementation of the method, it will directly call the implementation of this method, and pass all the parameters in the message to the method implementation. At the same time, it will pass two hidden parameters:

1. Message recipient object: The message recipient object can be referenced through self.

2. Method Selection: the method itself is referenced by _ cmd.

Although these parameters are not declared, they can still be referenced in the source code.

 

Dynamic Method Analysis:

1. Dynamic Method Analysis:

@ Dynamic property name; indicates the method that the compiler needs to dynamically generate the property.

You can implement resolveInstanceMethod: And resolveClassMethod: to dynamically implement the methods or class methods of the given object.

The OC method can be considered as a C function with at least two parameters self and _ cmd. You can use the class_addMethod method to add a function to the class method, as follows:

Void dynamicMethodIMP (id self, SEL _ cmd ){

// Implementation...

}

+ (BOOL) resolveInstanceMethod :( SEL) sel {

If (sel ==@ selector (resolveThisMethodDynamically )){

Class_addMethod ([self class], sel, (IMP) dynamicMethodIMP, "v @:");

Return YES;

}

Return [super resolveInstanceMethod: sel];

}

 

Before entering the message forwarding mechanism, respondsToSelector: And instancesRespondToSelector: Will be called first. You can provide an IMP for the selected token in the two methods. If you have implemented the resolveInstanceMethod: method but still want the normal message forwarding mechanism, you only need to return NO.

 

2. Dynamic Loading

The OC program can link and load new classes and category classes at runtime. The newly loaded class is no different from the class loaded when the program starts.

Dynamic Loading can be used in many places. For example, modules in the System Configuration are dynamically loaded.

 

Application scenarios:

In the Cocoa environment, dynamic loading is generally used to customize applications. It can load modules compiled by other programmers at runtime (similar to interface Build loading custom palette and system configuration program loading custom modules ). These modules expand their own programs in a licensed manner without the need to define or implement them themselves. I have provided the framework myself, and other programmers have provided the implementation.

 

Message forwarding:

1. Message forwarding

If an object receives a message that cannot be processed, the system sends a forwardInvocation: Message to the object before an error is thrown. The unique parameter of the message is an NSInvocation object, this object encapsulates the parameters of the original message and message. Therefore, the forwardInvocation method can be implemented to perform some default processing on messages that cannot be processed, or to prevent errors from being thrown in other ways.

When an object fails to respond to a message because it does not have a response method, the system will send a message to the object through forwardInvocation. Every object is integrated into forwardInvocation from the NSObject class: method. However, the method implementation in NSObject simply calls doerNotRecognizeSelector :. Implement your own forwardInvocation: In this method, you can forward messages to other objects.

Messages can be forwarded using the invokeWithTarget: method:

-(Void) forwardInvocation :( NSInvocation *) anInvocation {

If ([someOtherObject respondsToSelector: [anInvocation selector])

[AnInvocation invokeWithTarget: someOtherObject];

Else

[Super forwardInvocation: anInvocation];

}

ForwardInvocation: A method is like a distribution center for unrecognized messages and forwards these messages to different recipients. It can translate a message into another message, or simply "eat" some messages, so there is no response or error. ForwardInvocation: The method can also provide the same response to different messages, depending on the specific implementation of the method. This method provides the ability to link inaccessible objects to the message chain.

Note: forwardInvocation: The method is called only when the message receiving object cannot respond to the Message normally. Therefore, if you want your object to forward the clickBtn: Message to another object, Your object cannot have the clickBtn: method. Otherwise, forwardInvocation will not be called.

2. Message forwarding and multi-Inheritance

Message Forwarding is similar to integration and can be used to simulate multiple inheritance in OC programs. An object responds to a message through forwarding. It looks like the object has been borrowed from another class or "inherited" The method implementation. Use the forwardInvocation method to forward messages in a class to another class.

3. Message proxy object

4. Message forwarding and class inheritance

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.