iOS Development Low-level Knowledge--runtime detailed

Source: Internet
Author: User
Tags class definition instance method list of attributes
first, let's comb the bottom concept of the runtime, and if you want to see how it can be turned to the bottom. Brief Introduction

Runtime is also called runtime, is a set of low-level C language API, which is one of the core of IOS internal, we usually write the OC code, the bottom is based on it to achieve. Like what:

[Receiver message];
The underlying runtime is transformed by the compiler into:
objc_msgsend (receiver, selector)
//If there are parameters such as:
[receiver message: (ID) arg ...];
The underlying runtime is transformed by the compiler into:
objc_msgsend (receiver, selector, arg1, arg2, ...)

You may not be able to see its value, but what we need to know is that objective-c is a dynamic language that will put some work on the code when it is run rather than at compile time. That is, there are a lot of classes and member variables that we don't know when we compile, and at run time, the code we write is converted into a complete, determined code run.

Therefore, the compiler is not enough, we also need a run-time system (Runtime systems) to process the compiled code.

Runtime is basically written in C and remit, this shows Apple's efforts to make the dynamic system efficient. Apple and GNU maintain an open source version of Runtime, each of which is struggling to keep in line with each other in two versions.

Click here to download the open source code that Apple maintains. the role of Runtime

OBJC interacts with the Runtime system at three levels: by Objective-c source code through the NSObject class definition of Foundation framework Runtime source code via direct call to Objective-c library function

Most of the time we only need to write OC code, Runtime system automatically behind the scenes to do everything, remember the introduction if we call the method, the compiler will convert OC code to run-time code, at run time to determine the data structure and functions. methods defined by the NSObject class of the Foundation framework

Most of the classes in the Cocoa program are subclasses of the NSObject class, so they inherit the nsobject behavior. (Nsproxy class with exception, it is an abstract superclass)

In some cases, the NSObject class simply defines the template that completes something and does not provide the required code. For example, the-description method returns a string representation of the class content, which is used primarily to debug the program. The NSObject class does not know the contents of the subclass, so it simply returns the name of the class and the address of the object, and the subclass of the NSObject can be implemented again.

There are also nsobject ways to get information from the Runtime system and allow the object to examine itself. For example: The-class method returns the class of the object;-iskindofclass: And-ismemberofclass: Method checks whether the object exists in the inheritance system of the specified class (whether it is a subclass or a parent class or a member variable of the current class);- Respondstoselector: Checks whether the object can respond to the specified message;-conformstoprotocol: Checks if the object implements the method of the specified protocol class;-methodforselector: Returns the address of the specified method implementation. by direct invocation of the Runtime library function

The Runtime system is a dynamic shared library with a common interface. The header file is stored in the/USR/INCLUDE/OBJC directory, which means that we only need to introduce the Objc/runtime.h header file when we use it.

Many functions allow you to use pure C code to implement the same functionality in OBJC. Unless you're writing some OBJC and other language bridges or the underlying debug work, you don't normally use these C-language functions when writing OBJC code. What do you have for the public interface, which is described later. I will refer to Apple's official API documentation. some Runtime of the terms of the data structure

To fully understand the Runtime mechanism, we must first understand some of the terms of Runtime, they all correspond to the data structure. SEL

It is the Selector in OBJC (Swift is the Selector Class). Selector is the method selector, in fact, the role is the same as the name, in daily life, we identify who is who by name, note that OBJC in the same class will not have the same two methods. Selector the method name in order to find the corresponding method implementation. Its data structure is:

typedef struct OBJC_SELECTOR *sel;

We can see that it's a C string mapped to a method, and you can get a sel-type method selector by objc the compiler command @selector () or the Sel_registername function of the Runtime system.

Attention:
Methods with the same name in different selector are the same, and because of the variable types, they do not cause them to invoke the method to achieve confusion. ID

An ID is a parameter type, which is a pointer to an instance of a class. The definition is as follows:

typedef struct OBJC_OBJECT *id;
struct Objc_object {Class isa;};

With this definition, you see that the OBJC_OBJECT structure contains an ISA pointer that can be found by the ISA pointer to the class to which the object belongs.

Attention:
The ISA pointer does not always point to the type that the instance object belongs to when the code is run, so you cannot rely on it to determine the type, or you need to use the-class method of the object.

The PS:KVO mechanism is to point the object's ISA pointer to an intermediate class rather than the real one, as described in the KVO chapter. Class

typedef struct OBJC_CLASS *class;

Class is actually a pointer to the OBJC_CLASS structure. The data structure of Objc_class is as follows:

struct Objc_class {
    class Isa  objc_isa_availability;

#if!__objc2__
    Class super_class                                        objc2_unavailable;
    const char *name                                         objc2_unavailable;
    Long version                                             objc2_unavailable;
    Long info                                                objc2_unavailable;
    Long instance_size                                       objc2_unavailable;
    struct objc_ivar_list *ivars                             objc2_unavailable;
    struct objc_method_list **methodlists                    objc2_unavailable;
    struct Objc_cache *cache                                 objc2_unavailable;
    struct objc_protocol_list *protocols                     objc2_unavailable;
#endif

} objc2_unavailable;

As you can see from Objc_class, a Run-time class has its parent class pointer, class name, member variable, method, cache, and attached protocol associated with it.

Where Objc_ivar_list and objc_method_list are list of member variables and method lists, respectively:

Member variable list
struct objc_ivar_list {
    int ivar_count                                           objc2_unavailable;
#ifdef __lp64__
    int space                                                objc2_unavailable;
#endif
    /* Variable length structure * *
    struct Objc_ivar ivar_list[1]                            objc2_unavailable;                                                            objc2_unavailable;

Method List
struct Objc_method_list {
    struct objc_method_list *obsolete                        objc2_unavailable;

    int Method_count                                         objc2_unavailable;
#ifdef __lp64__
    int space                                                objc2_unavailable;
#endif
    /* Variable length structure * *
    struct Objc_method method_list[1]                        objc2_unavailable;

This shows that we can dynamically modify the value of *methodlist to add member methods, which is also the principle of Category implementation, also explains the Category can not add the reason for the attribute. Here we can refer to the article of the technical Team of the American Regiment: Deep Understanding Objective-c: Category.

The objc_ivar_list structure is used to store a list of member variables, while Objc_ivar stores the information of a single member variable; Similarly, the objc_method_list structure stores a list of method arrays, while the information for a single method is determined by the Objc_method The structure body is stored.

Notably, the Objc_class also has an Isa pointer, which shows that the OBJC class itself is also an object. To handle the relationship between classes and objects, the Runtime library creates something called the Meta Class (the Metamodel), and the class to which the class object belongs is called the Meta class. Meta class describes the metadata that the class object itself has.

The class method that we are familiar with is derived from the Meta class. We can understand that the class method is the instance method of the Class object. Each class has only one class object, and each class object has only one meta class associated with it.

When you send a message similar to [NSObject Alloc] (class method), the message is actually sent to a class object (class object), which must be an instance of a class, and this class is also a root class (root meta classes). The instance. The ISA pointers for all the meta classes end up pointing to the root class.

So when [NSObject alloc] This message is sent to the class object, the Run-time code objc_msgsend () will go to its meta class to find a way to respond to the message, and if found, it will execute the method call on the class object.

The above image implementation is the Super_class pointer, and the dotted line ISA pointer. And the parent of the root class is nsobject,isa points to itself. And NSObject does not have a parent class.

Finally, there is a objc_cache in the Objc_class, the cache, its role is very important, will be mentioned later. method

Method represents the type of one of the methods in a class

typedef struct OBJC_METHOD *method;

struct Objc_method {
    SEL method_name                                          objc2_unavailable;
    Char *method_types                                       objc2_unavailable;
    IMP method_imp                                           objc2_unavailable;
}

Objc_method stores the method name, method type and method implementation: The method name type is the SEL method type method_types is a char pointer, and the parameter type of the storage method and the return value type Method_imp point to the implementation of the method, essentially a function pointer I var

Ivar is the type that represents the member variable.

typedef struct OBJC_IVAR *ivar;

struct Objc_ivar {
    char *ivar_name                                          objc2_unavailable;
    Char *ivar_type                                          objc2_unavailable;
    int Ivar_offset                                          objc2_unavailable;
#ifdef __lp64__
    int space                                                objc2_unavailable;
#endif
}

Where Ivar_offset is the base address offset byte IMP

The definition of imp in objc.h is:

typedef ID (*IMP) (ID, SEL, ...);

It is a function pointer, which is generated by the compiler. When you initiate a OBJC message, the code that it will eventually execute is specified by the function pointer. The function pointer of IMP points to the implementation of this method.

If we get a portal that executes a method of an instance, we can bypass the message passing phase and execute the method directly, as mentioned in the Cache below.

You will find that IMP points to the same method as the Objc_msgsend function type, with parameters containing ID and SEL types. Each method name corresponds to a SEL-type method selector, and the SEL-corresponding method implementation of each instance object is certainly unique, with a set of IDs and SEL parameters to determine the unique method implementation address.

A determined method also has only a single set of IDs and SEL parameters. Cache

The Cache definition is as follows:

typedef struct Objc_cache *cache

struct Objc_cache {unsigned
    int mask/* Total = mask + 1 */                 OBJC2_UNAVAILABL E;
    unsigned int occupied                                    objc2_unavailable;
    Method Buckets[1]                                        objc2_unavailable;

Cache optimizes the performance of the method invocation, and whenever an instance object receives a message, it does not traverse the method list of the class to which the ISA pointer refers to find the method that can respond, because each time the lookup is too inefficient, it is preferred to look in the Cache.

The Runtime system saves the invoked method to the Cache, and if a method is invoked, it is likely to be invoked in the future and will be more efficient the next time it is searched. Just like the computer composition principle, the CPU bypasses main memory and accesses the Cache first. Property

typedef struct OBJC_PROPERTY *property;
typedef struct OBJC_PROPERTY *objc_property_t;//This more commonly used

Properties in classes and protocols can be obtained through the Class_copypropertylist and Protocol_copypropertylist methods:

objc_property_t *class_copypropertylist (class cls, unsigned int *outcount)
objc_property_t *protocol_ Copypropertylist (Protocol *proto, unsigned int *outcount)

Attention:
Returns a list of attributes in which each element is a objc_property_t pointer

#import <Foundation/Foundation.h>

@interface person:nsobject

/** name *
/@property (Strong, nonatomic) NSString *name;

/** Age *
/@property (assign, nonatomic) int age;

/** Weight * * *
@property (
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.