OBJECTIVE-C Runtime Mechanism detailed

Source: Internet
Author: User



Objective-c language is a dynamic language that puts a lot of static language in the process of compiling and linking things to the runtime. At the same time OC is also a simple language, a large part of the content of C, just add the language level of the keyword and grammar, really make OC powerful is its running, it is very small but very powerful, wherein the core is the message distribution. The advantage of this dynamic language is that we are more flexible in writing code, such as the ability to forward messages to the object we want, or to exchange the implementation of a method at will.



This feature means that OC requires not only a compiler, but also a runtime system to execute the compiled code. For OC, this runtime system is like an operating system. This runtime system is the runtime, written in C and sink, this library makes C language has the object-oriented ability. The most important of these is the message mechanism. In the case of C, the call of a function is compiled to determine which function to invoke, and the sequence executes after the compilation is complete, without any ambiguity. The function call of OC is called message sending, which belongs to the dynamic calling procedure. It is not possible at compile time to decide which function to call actually (it turns out that OC can call any function during the compile phase, even if the function is not implemented, as long as it is declared without an error.) The C language will error in the compilation phase. The function is called only when it is actually running, based on the name of the function.



In a word: We write the OC Code, program running process, is actually converted to runtime C language code, runtime is OC behind the scenes workers. runtime belongs to the lower level of OC and can perform very low level operations (OC is not possible). )



The runtime library mainly does the following several things:



1. Encapsulation: In this library, objects can be represented in the struct in C, and methods can be implemented with C functions, plus some additional features. Once these structures and functions are encapsulated by the runtime function, we can create, inspect, modify classes, objects, and their methods while the program is running.



2. Find out the final execution code of the method: when the program executes [object DoSomething], a message (dosomething) is sent to the message Receiver (object), and the runtime responds differently depending on whether the message receiver can respond to the message.






OC Runtime is currently available in two versions: modern runtime and Legacy runtime. The modern runtime is used primarily for 64-bit applications. The Legacy runtime is used primarily for 32-bit applications. It is now generally 64-bit.



On the issue of execution efficiency, "static language execution efficiency is higher than dynamic language" should be no problem. Because part of the CPU computation loss is in runtime.



How does OC implement dynamic invocation? If you write the following code in OC:





[obj Maketext];





Where obj is an object and Maketext is a function name. Executing a method, some languages, the compiler performs some additional optimizations and error checking because the invocation relationship is straightforward and obvious. But for message distribution it's less obvious that you don't have to know whether an object can handle a message before sending it. You send the message to him, he may deal with it, or it may be transferred to another object for processing. A message does not have to correspond to a method, and an object may implement a method to handle multiple messages.



At compile time, runtime translates the above code into:





Objc_msgsend (obj, @selector (maketext));





So actually





Objc_msgsend (obj, @selector (Maketext)), and <pre name= "code" class= "plain" >[obj Maketext];
is equivalent.


Another example:
[obj settt:@ "111" isok:yes];
And
Objc_msgsend (obj, @selector (settt:isok:), @ "111", YES)
is also equivalent. Note the expression of an OC function name with parameters.










First, let's take a look at the Obj object, which is inherited from NSObject in iOS.





@interface nsobject{Class Isa objc_isa_availability}

There is a class Isa pointer in the NSObject. Then let's look at what class is: This is defined in objc.h.







typedef struct objc_class * Class;
struct objc_class {

  Class isa; // Point to metaclass


  Class super_class; // Point to the parent class

  const char * name; // Class name

  long version; // The version information of the class, the initial default is 0, you can modify and read through the runtime functions class_setVersion and class_getVersion

  long info; // Some identification information, such as CLS_CLASS (0x1L) indicates that the class is an ordinary 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 size of the instance variables of this class (including the instance variables inherited from the parent class);

  struct objc_ivar_list * ivars; // Used to store the address of each member variable;

  struct objc_method_list ** methodLists; // related to some flags of info, such as CLS_CLASS (0x1L), then store object methods;

  struct objc_cache * cache; // Pointer to the most recently used method to improve efficiency;

  struct objc_protocol_list * protocols; // store the protocol that this class complies with;
} 








For a class, there are a lot of things we can do to explain something important:



Class Isa: Point to Metaclass, which is the static class. In general, ISA in an Obj object points to the normal class, which stores ordinary member variables and object methods (-the first method), the ISA pointer in the normal class points to the static class, and the static class stores statically type member variables and class methods (+ The beginning of the method).






Class Super_class: Points to the parent class, or null if the class is a root class.



We understand the inheritance relationships of classes and objects by using the following diagram:








Note: The ISA pointer in all metaclass points to the root metaclass (that is, Root Class Meta), while the root metaclass points to itself. Root Metaclass is generated by inheriting the root class. is consistent with the root class structure member, which is the structure mentioned earlier. The difference is that the ISA pointer to root metaclass points to itself.






Then take a look at the method:



@selector (Maketext): This is an Sel method selector. The main function of SEL is to find the function pointer of the corresponding method by means of the method name (Maketext), and then call its function. The SEL itself is an address of type int, with the name of the method stored in the address. For a class, each method corresponds to an sel. So there cannot be 2 identical methods in the iOS class, even if the parameter types are different because the SEL is generated from the method name, the same method name can only correspond to one sel. At the same time, we should also know that OC is not overloaded with methods.






Let's take a look at how the specific message is sent to dynamically find the corresponding method.



First, the compiler converts the code [obj Maketext] into objc_msgsend (obj, @selector (Maketext)), and in the Objc_msgsend function, first finds the corresponding class through the ISA pointer of obj. In class first go to the cache through the SEL to find the corresponding function method, if the cache is not found, then go to methodlist find, if not found in MethodList, then take superclass to find. If found, the method is added to the cache to facilitate the next lookup, and the function pointer in method jumps to the corresponding function to execute.



The class method list is actually a dictionary, and key is selector,value as the IMP function pointer. An IMP is an implementation that points to the method in memory. It is important that the relationship between selector and Imp is determined at run time, not at compile time.






For object-oriented purposes, everything is object, and in OC, the class is also an object. The class is Object, which can also handle messages. So you now know why there are class methods and instance methods.






Method swizzling



As we've said above, the method consists of two parts. Selector equivalent to a method of id,imp is the implementation of the method. One traversal of this separation is that the correspondence between selector and IMP can be changed. For example, an IMP can have multiple selectors pointing to it.



The method swizzling can exchange two implementations. In OC, there are two ways to extend class. The first is subclass. You can override a method to invoke the implementation of the parent class, which also means that you must use this subclass instance. But if we use category classification, after rewriting a method, we can no longer invoke the original method.



Method swizzling can solve this problem, you can rewrite a method without inheriting, but also can invoke the original implementation. A common practice is to add a method to the category that can be exchanged by method_exchangeimplementations the runtime method.



















































Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.



OBJECTIVE-C Runtime Mechanism detailed


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.