Summary of common examples of iOS development runtime

Source: Internet
Author: User
Tags instance method

Often have small partners privately in Q asked some things about the runtime , asked if I have runtime related blog, before really did not serious summed up. Before just parsing the third-party framework source code, talked about some usage, that is, these third-party framework used in the runtime. such as attribute associations, dynamic acquisition of properties, and so on. This blog on the theme of the runtime to summarize some of its commonly used methods, of course, "empty talk endangers", today's blog chat about the runtime still depends on this blog involved in the demo.

The content of the runtime discussed in this blog is about: dynamically get the class name , the member variable of the dynamic Get class, the property list of the dynamic get class, the method list of the dynamic fetch class, Dynamic acquisition of the list of protocols followed by the class , Dynamic addition of new methods , class of instance method implementation of the Exchange , Dynamic Property Association , message sending and message forwarding mechanism . Of course, this blog summarizes the functions that are commonly used at runtime, not all runtime content.

First, build runtime test Cases

The content of this blog is based on the example, so we build our test class in this blog,Runtime will be related to the operation of the class. Below is the catalogue of Demos involved in this blog, the above Runtimekit class is to speak the Runtime commonly used functions for a simple package, and the bottom of the TestClass And the related classes are the objects that our Runtime wants to manipulate. The TestClass and the contents of the category are described in detail below.

  

These are the main parts of our test class TestClass , because TestClass is designed to test the class, so its content should be as comprehensive as possible. TestClass followed the nscoding, nscopying The two protocols, and added public properties , private properties , Private member variables , public instance methods, private instance methods, class methods, and so on. These additions will be the object of our runtime's operations. Some of the testclass below will be introduced later when using runtime.

  

  

  

Second, the Runtimekit package

Let's take a look at the content in Runtimekit , which is a simple encapsulation of the usual methods of Runtime . It is mainly the dynamic acquisition of some properties and methods of the class, as well as the dynamic method of adding and exchanging methods. This part of the dry goods are still a lot of.

1. Get the class name

It is relatively simple to get the class name dynamically, and you can use Class_getname (Class) to get the name of the class at run time. The class_getname () function returns a pointer of type char , which is the string type of the C language, so we want to convert it to the NSString type and then go back. Below +fetchclassname: The method is the method that we encapsulate to get the class name, as follows:

  

2. Get member variables

Below this +fetchivarlist: This method is the method that we encapsulate to get the member variables of the class. Of course, when we get member variables, we can use ivar_gettypeencoding () to get the type of the corresponding member variable. Use ivar_getname () to get the name of the corresponding member variable. Below is the encapsulation of the function that gets the member variable. An array is returned, the element of the array is a dictionary, and the dictionary stores the name and type of the corresponding member variable.

  

Below is the member variable of the TestClass class that was obtained by calling the above method. Of course there are no private and public points at runtime, as long as the member variables are available. Adding a member property to a class in OC is actually adding a member variable and getter and setter method. A member property is definitely in the obtained member list, but the name of the member property is preceded by an underscore to differentiate it from the member property. We can also get the type of the member variable, the _var1 below is the Nsinteger type, dynamically gets the Q letter, is actually the nsinteger symbol. while I represents the int type ,C represents the bool type ,D represents the double type , and F represents thefloat type . Of course, these basic types are replaced by a single letter, if it is a reference type, it is directly a string, such as the Nsarray type is "@NSArray".

  

3. Get member properties

The above gets the member variables of the class, then this +fetchpropertylist: Gets the member property. Of course, the only members that get at the moment are the member properties, which are the member variables that have setter or getter methods. The following is primarily a list of properties that are obtained using class_copypropertylist (Class,&count) , and then through the for loop through the property_getname () To get the name of each property. Of course, the name obtained by using property_getname () is still a pointer to the C language Char type, so we also need to convert it to the NSString type, and then put it back in the array. As shown below:

  

This is the call to the above method to get all the properties of the TestClass, of course Dynamicaddproperty is we use Runtime dynamic to add to TestClass , So you can get it too. Of course we get the name of the property to distinguish it from its corresponding member variable, and the name of the member property is not underlined in front of it.

  

4. Get the instance method of the class

And then we'll wrap it up. The ability to get a list of instance methods of a class, below this +fetchmethodlist: is the function that we encapsulate to get the list of instance methods of the class. In the lower function, get the instance method list of the class through the Class_copymethodlist () method, and then use method_getname () for the For loop to get the name of each method. The name of the method is then converted to the NSString type, which is stored in the array and returned. The specific code looks like this:

  

This is the result of the above method running on TestClass, where all instance methods of the TestClass class are printed, and of course the getter and setter methods that contain the member properties must be included. Of course, the methods in the TestClass category must also be available. The results are as follows:

  

5. Get the list of agreements

Below is a way to get the list of protocols that our class follows, mainly using class_copyprotocollist () to get the list, and then using protocol_getname () for sequential use to get the name of the Protocol, Finally, it is converted to the NSString type into the array to return.

  

Below is a list of the protocols that we have followed for the TestClass class:

  

6. Dynamic addition method implementation

Below is the dynamic way to add methods and implementations to the corresponding classes. The +addmethod method below has three parameters, the first parameter is the class to add the method, the second parameter is the SEL of the method, and the third parameter is the selthat provides the method implementation. The methods below are used later when sending messages and forwarding messages. The following methods are mainly used to obtain the corresponding SEL method with Class_getinstancemethod () and method_getimplementation () . The IMP below is actually the implementation method abbreviation, gets to the corresponding method implementation, and then calls the Class_addmethod () method to The IMP binds to the SEL . The practice is shown below.

  

7, the method realizes the Exchange

Below is the implementation of the two methods of the lecture class to Exchange. If the MethodA is exchanged with the MethodB method Implementation, the MethodB content is executed when the MethodA is called, and vice versa.

  

The code below is a test of the above method. Below is a class of TestClass, in which the methods in the class are replaced with the methods in the TestClass. That is, replace the method1 with the METHOD2, and the method2 that is called in Method2 is actually the method1 of the call. This feature is often used in third-party libraries and has been achieved for AOP programming purposes.

  

Third, attribute Association

Attribute Association It is in the class of the dynamic to add the corresponding properties for our class, if you have seen the previous release of the masonry Framework Source parsing blog, the underlying attribute association is not unfamiliar. In the masonry framework, a constraint array is added to the UIView in the UIView class using the Runtime 's attribute association, which is used to record additions to the current View all constraints on the. Below is the TestClass in the category of the Objc_getassociatedobject () and Objc_setassociatedobject () two methods to The TestClass class adds a dynamicaddproperty property. The list of properties we obtained above contains the member properties that were added dynamically.

Below is the specific code for the property association, as shown below.

  

Iv. message processing and message forwarding

What you have to mention in runtime is the message processing and message forwarding mechanism of OC. Of course, there are a lot of relevant information on the Internet, this blog for completeness, or to talk about message processing and message forwarding. when you invoke a method of a class, the query is made in the method cache list in this class, and if the implementation of the method is found in the cache list, it is executed if it is not found in the party list in this class. The call is made after finding the appropriate method implementation in the list of this class, and if it is not found, it is searched in the parent class. If the implementation of the corresponding method is found in the list of methods in the parent class, execute it, or perform the steps below .

When calling a method in the cache list, the list of methods in this class, and the method list of the parent class cannot find the corresponding implementation, there are a few steps in the middle of the program crash phase that you can save. Let's take a look at how these steps should be followed.

1. Message processing (Resolve Method)

+resolveinstancemethod is executed when the class method implementation is not found in the corresponding class and in the parent class : this class method. If the method is not overridden in a class, the default returns No. If you return no, it means that you do not do any processing and take the next step. If you return YES , it means that the method that cannot find the implementation is processed in this method. In this method, we can add a method implementation for the SEL that cannot find the implementation, and after adding it, we will implement the method we added. This way, when a class calls a method that does not exist, it does not crash. The practice is as follows:

  

2. Fast message forwarding

If the above message is not processed, that is +resolveinstancemethod: Return no , will go to the next step of message forwarding, that is, -forwardingtargetforselector:. The method returns an object of a class that has an implementation of the SEL corresponding to the object, which is forwarded to the Secondclass for processing when it calls the missing method. This is called message forwarding. When the method returns self or nil, stating that the corresponding method is not forwarded, then it is time to go to the next step.

  

3. Message General Forwarding

If you do not forward the message to an object of another class, you can only handle it yourself. If the above method returns self, the -methodsignatureforselector: method is executed to get the parameter of the method and the return data type, which means that the method obtains the signature of the method and returns it. If the above method returns nil, then the message is forwarded to the end, the program crashes, and the report cannot find the corresponding method to implement the crash information.

In +resolveinstancemethod: return No when the following method will be executed, below is also said that the method is forwarded to Secondclass, as follows:

  

Today's blog first come here, of course, there are some other Runtime things this blog does not involve, if later to parse the source code of the repository encountered, we are talking alone. By convention, the demo that this blog is attached to will still be shared on Github , and below is a link to share.

GitHub source Share Link:https://github.com/lizelu/ObjCRuntimeDemo

Summary of common examples of iOS development runtime

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.