IOS Runtime Explore (i): Starting from runtime understanding object-oriented classes to process-oriented structures

Source: Internet
Author: User

You know, the runtime is here.

Reprint please specify the source http://blog.csdn.net/u014205968/article/details/67639205

This article mainly explains the runtime related knowledge, from the principle to the practice, because contains the content to be divided into the following five articles to explain in detail, may choose the direction which needs to understand by oneself:

    • Starting from Runtime: Understanding object-oriented classes to process-oriented structures
    • Starting from Runtime: in-depth understanding of the OC message forwarding mechanism
    • Starting from Runtime: Understanding the properties of OC
    • Starting from Runtime: Practice category Add attribute and black Magic method swizzling
    • Starting from Runtime: in-depth weak implementation mechanism

This article is the first article in a series of articles starting from Runtime: Understanding object-oriented classes to process-oriented structures, mainly from the runtime start to explain how the object-oriented class is transformed into a process-oriented structure, to explore the processing of OC class nature.

What is runtime

runtimeIs the runtime, there are not many scenarios to use in actual development runtime , but understanding runtime helps us to better understand the principles of OC, thus improving the level of development.
runtimeVery powerful, is the most important part of OC is the biggest feature of OC, can not exaggerate the runtime achievement of OC, although runtime it is a module of OC.
We all know that high-level programming languages want to be executable files need to be compiled into assembly language and then assembled into machine language, machine language is the only language that the computer can recognize, but OC can not be directly compiled into assembly language, but first to the pure C language and then compile and assemble the operation, The transition from OC to C is runtime achieved. However, we use OC for object-oriented development, and the C language is more process-oriented development, which requires the transformation of object-oriented class into a process-oriented structure, this article is through the runtime source analysis to explain runtime how to transform the object-oriented class into a process-oriented structure.

In-depth code understanding instance, class object, Metaclass

In object-oriented programming, the most important concept is the class, and let's start with the code to see how OC implements the class.

The previous article has been talking about runtime transforming an object-oriented class into a process-oriented struct, what exactly does this struct look like? Open #import<objc/objc.h> The file, you can find the following lines of code

/// An opaque type that represents an Objective-C class.struct objc_class *Class;/// Represents an instance of a class.struct objc_object {    Class isa  OBJC_ISA_AVAILABILITY;};/// A pointer to an instance of a class.struct objc_object *id;

It is not difficult to see through comments and code that an object or instance we create is actually a struct, and that is the pointer to the struct objc_object struct we use id . The following code is available:

//以下两种写法都成立id str = [[NSString alloc] init];NSString *str = [[NSString alloc] init];

As you can see from the above code, the instance we create NSString类 str is actually a struct objc_object struct pointer, so whether it's a Foundation class in the framework or a custom class, the instance of the class we created finally gets a struct pointer, and the struct has only one member variable that is The Class pointer to the type isa , is the Class struct pointer, pointing struct objc_class , what is the structure of the body? Here is a word str is a NSString , plus the Class name of the pointer, we are not difficult to guess, Class is to represent NSString this class.
The next step is to explain the structure in detail, and now we'll look at another example, and sometimes we'll create an instance by the following method:

NSString *str = [[NSString alloc] initWithString: @"Hello World"];Class c = [str class];NSString *str2 = [[c alloc] initWithString: @"Hello World"];

As you may have discovered, by invoking a method from an instance object, class we are able to get a variable of a Class type that we can use Class to create the corresponding instance object.
In fact, the class in OC is also an object, called the 类对象 method obtained by the [str class] method above NSString类 类对象 , and then we can create an instance object through this, 类对象 then what is this 类对象 ? Open the #import<objc/runtime.h> file, we can find the structure struct objc_class of the definition, the structure is defined as follows:

The file objc/runtime.h is defined as follows:structObjc_class {class ISA objc_isa_availability; Class Super_classConst Char*nameLongVersionLongInfoLongInstance_sizestructObjc_ivar_list *ivarsstructObjc_method_list **methodlistsstructObjc_cache *cachestructObjc_protocol_list *protocols}/ * use ' Class ' instead of ' struct objc_class * ' * *The file Objc/objc.h file has the following definition/a   opaque type that represents an Objective-c class.typedefstructObjc_class *class;//   represents an instance of a class.structObjc_object {Class isa objc_isa_availability;};  /A pointer to an instance of a class.typedefstructObjc_object *id;

struct objc_classstruct defines a lot of variables, it is not difficult to find out by name, the structure of the pointer to the parent class, the name of the class, version, instance size, instance variable list, method list, cache, followed by the list of protocols, such as a class containing information is not it? Yes, it 类对象 is a struct struct objc_class , the data stored in this structure is called 元数据(metadata) , the first member variable of the struct is also isa a pointer, which means that Class itself is actually an object, so we call it 类对象 , 类对象 Generated for creating instance objects at compile time, is a singleton.

类对象is the 元数据 information about how to create an instance, 类对象 and 类方法 where should it be created? is to isa create from the struct that the pointer points to, and 类对象 the isa pointer points to what we call the 元类(metaclass) 元类 creation 类对象 and all the 类方法 information needed, so the entire structure should look like this:

We can clearly see that an instance object is the struct whose pointer points to the Meta class, the pointer to the struct objc_object isa 类对象 类对象 isa super_class parent class, 类对象 and 元类 the pointer to the super_class parent class 元类 . 元类 isa and what does that pointer point to? For a clearer expression, direct use of a large God-drawn figure.

We can see that the whole system constitutes a self-closing loop, if it is inherited from the middle NSObject Root class NSObject . At this point, the whole 实例 , 类对象 and 元类 The concept is clear, and then we look at the code to see how these concepts should be applied.

 @interface  Person: nsobject @property(nonatomic, copy)NSString* NAME;@property(nonatomic,Assign) Nsuinteger age;@end @implementation   person@synthesizename = _name;@synthesizeage = _age;@endintMainintargcConst Char* argv[]) {@autoreleasepool {person *p = [[Person alloc] init];        Class C1 = [P class]; Class C2 = [Person class];//Output 1        NSLog(@"%d", C1 = = C2); }return 0;}

c1Is obtained through an instance object Class , the instance object can get to it 类对象 , the class is represented by the recipient of the message 类对象 , so the class object gets Class its own, and also confirms that it 类对象 is a singleton idea.
So what if we want to get isa pointers to objects?

Introducing two functions

class_isMetaClass(Class cls)     OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0)object_getClass(id obj)     OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0);

class_isMetaClassUsed to determine whether an object is a pointer to an object that is Class 元类 object_getClass used to get an object isa .

Then look at the following code:

intMainintargcConst Char* argv[]) {@autoreleasepool{Person *p = [[Person alloc] init];//Output 1NSLog (@"%d", [Pclass] = = Object_getclass (p));//Output 0NSLog (@"%d", Class_ismetaclass (Object_getclass (P)));//Output 1NSLog (@"%d", Class_ismetaclass (Object_getclass ([personclass])));//Output 0NSLog (@"%d", Object_getclass (p) = = Object_getclass ([personclass])); }return 0;}

As you can see from the code, an instance object is obtained by means of a pointer to the class Class object It is pointing to, isa 类对象 not the pointer to 类对象 元类 类对象 isa 元类 .

Summarize

From the code analysis above, we have learned how classes and instances in OC are mapped to the C-language structure, the instance object is a struct, the struct has only one member variable, which is the object that constructs it, and this class object stores all the information that the instance object needs including instance variables, instance methods, etc. The class object is created from a meta class, where class variables and class methods are preserved, which perfectly explains how the entire class and instance are mapped to the struct body.

Next

Understanding class-to-struct mapping is only runtime the first step in uncovering the mystery, and the next blog will describe the message passing mechanism of OC and the runtime specific operations that are done on OC messaging, and interested readers can continue to learn the next article from Runtime: an in-depth understanding of the OC message forwarding mechanism.

Note

Due to the limited level of the author, there are inevitably flaws, if there are problems please enlighten.

IOS Runtime Explore (i): Starting from runtime understanding object-oriented classes to process-oriented structures

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.