The runtime runtime mechanism for iOS

Source: Internet
Author: User
Tags vars

This article turns from http://www.cnblogs.com/guoxiao/p/3583432.html

Recently, I've been working on the runtime mechanism, and I think there's probably a lot of people who don't know that. I am here to share with you my understanding of the runtime mechanism.

To understand runtime, we first understand the internal structure of classes and objects, and we will first describe the hierarchy of classes and objects in the lower OC.

First, the definition of class and object is found from the runtime.h header file.
An opaque type, represents an objective-c class.typedef struct Objc_class *class;///represents an instance of a C Lass.struct objc_object {    Class isa;};/ A pointer to an instance of a class.typedef struct objc_object *id;

Thus, the class is a pointer to the Objc_class struct, and the ID is a pointer to the Objc_object struct, whose member Isa is a pointer to the Objec_class struct body.

Second, let's look at the definition of Objc_class in the header file.
struct Objc_class {        class Isa;//points to Metaclass class                Super_class;//points to its parent class        const char *name;//class name        Long V ersion; Class version information, initialization defaults to 0, can be modified by the runtime function class_setversion and class_getversion, read        long info;//Some identification information, such as Cls_class (0X1L) Indicates that the class is a normal class, which contains object methods and member variables; Cls_meta (0x2l) indicates that the class is Metaclass, which contains class methods;        Long instance_size; The instance variable size of the class (including instance variables inherited from the parent class);        struct Objc_ivar_list *ivars; The address for storing each member variable is a        struct objc_method_list **methodlists;//related to some flag bits of info, such as Cls_class (0x1l), the method of storing objects, such as Cls_meta ( 0X2L), the storage class method;        struct Objc_cache *cache; A pointer to the most recently used method to increase efficiency;        struct objc_protocol_list *protocols;//Store the protocol that the class adheres to    }

Thus, the structure of the analogy object more than a large number of members, the following detailed introduction of the following Objec_class members:

The class structure pointed to by the ISA pointer in Isa:objec_object (object) is called Class (that is, the class to which the object belongs), which holds the normal member variable and the method of the object method ("-"), but here the class structure pointed to by the ISA pointer is called Metaclass, A method that holds a member variable of type static and a method of static type ("+").

Super_class: A pointer to the parent class of the class, and if the class is a root class (such as NSObject or Nsproxy), then Super_class is null.

Below, we can see the inheritance hierarchy relationship between classes and objects in OC by a graph:

Note: The ISA pointer in all metaclass points to the root metaclass, and the root metaclass points to itself. The root metaclass is generated by inheriting the root class, consistent with the members of the root class struct, and different from the ISA pointer of the root metaclass pointing to itself.

1. When we call an object method of an object, it finds the method first in the class methodlists that the ISA pointer points to itself, and if it is not found, it finds its parent class through the class's Super_class pointer. The method is then looked up from its methodlists, and if it is still not found, it continues to be looked up through the Super_class parent structure body, up to the root class;

2, when we call a class method, it will first find the metaclass through its own ISA pointer, and find the class method from its methodlists, if not found through Metaclass super_ The class pointer finds the Metaclass struct of the parent class, and then finds the method from the methodlists, and if it is still not found, continues to look up through the Super_class to the parent class structure until the root metaclass;

After the above introduction, I believe that you have been in OC object and class structure of the hierarchy has a further understanding. We'll show you how to use the runtime mechanism later.

Because OC is a run-time language, the type of the object is determined only when the program is running, and the method corresponding to the object is called. The runtime mechanism allows us to dynamically modify all the properties and methods of a class, an object, while the program is running.

The following is a simple way to use the runtime to convert a Dictionary object to a model. Of course, you may ask, I use KVO direct call Setvaluesforkeyswithdictionary: method, passed in a dictionary as quickly as possible to the dictionary to the model Ah, but this method has its drawbacks, only to traverse the model of all the member variables, The corresponding value is then removed from the dictionary by the member variable and the most secure assignment, otherwise the error occurs when the number of attributes in the model is different from the number of keys in the dictionary. Moreover, because runtime is a lower-level language, we write the OC code at run time, the compiler will first into the C and C + + code, and then execute, so the runtime mechanism, the performance of the program will be better. Having said so much, the following is a preliminary understanding of the power of the runtime.

First, we define a class

@interface person:nsobject{    cgfloat height;} @property (nonatomic, copy) NSString *name; @property (nonatomic, strong) NSNumber *age; @property (nonatomic, assign) int n o; @end

Then we use this class in other files, note that before using it, include #import <objc/message.h>

The following is a small piece of code to get to all the member variables in the class above

unsigned int outcount = 0;    Ivar *vars = Class_copyivarlist ([lender class], &outcount); Get to all member variable list        //traverse all member variables for    (int i = 0; i < Outcount; i++) {        Ivar Ivar = vars[i];//Remove member variable                of position I const char *propertyname = Ivar_getname (Ivar); Gets the variable name        const char *propertytype = ivar_gettypeencoding (Ivar);//Gets the variable encoding type        printf ("---%s--%s\n", PropertyName , propertyType);    }

Printing results:

---height--f[email protected] "nsstring" [email protected] "NSNumber"---_no--i

As you can see, the simple code above allows you to get the names and types of all the variables in a class, and then assign a value to a member variable of a specific object by using the Object_setivar () method.

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.