The object model and runtime mechanism of OBJECTIVE-C

Source: Internet
Author: User

Table of Contents
    • Object model (structure definition, class object, Meta class, and instance object relationships)
    • Message delivery and forwarding mechanisms
    • Runtime System Functional Understanding
Object model Structure Definition

objects (object): The basic construction unit (building block) in OC for storing and transmitting data.

You can find the definition of the object structure in the Objc.h file, as shown below, where the object structure is Isa of class type, and class is the Objc_class struct type pointer. Objc_class is the class object structure that we understand, and it also contains an Isa class object structure pointer.

类和对象的最终实现都是一种数据结构,(subclass is an instance of superclass)

    • Object structure
/// Represents an instance of a class.struct objc_object {    Class isa  OBJC_ISA_AVAILABILITY;};
    • ID type definition
/// A pointer to an instance of a class.typedefstruct objc_object *id;
    • Class type definition
/// An opaque type that represents an Objective-C class.struct objc_class *Class;
    • Class (object) structure
structObjc_class {class ISA objc_isa_availability;#if !__objc2__Class Super_class objc2_unavailable;Const Char*name objc2_unavailable;LongVersion objc2_unavailable;LongInfo objc2_unavailable;LongInstance_size objc2_unavailable;structObjc_ivar_list *ivars objc2_unavailable;structObjc_method_list **methodlists objc2_unavailable;structObjc_cache *cache objc2_unavailable;structObjc_protocol_list *protocols objc2_unavailable;#endif } objc2_unavailable;
Relationship of Class (class object), meta-Class (Meta-class object), and instance object

A complete class should include class methods, instance methods, and member variables (instance variables), each of which includes an Isa (is a class) pointer to the class object ( 运行时方法发送给对象消息,才确定类别并调用相应的方法实现 ), and all information about the class is documented in the class object structure.

The class object's Isa points to the tuple object (meta Class), the method list in the class object is an instance method (-, instance methods), and the method list in the meta-class object is the class method (+, class methods)

    • You can understand this:

      Classes include class objects and meta-class objects, which are defined by the class object structure to form all of the information for the class. When you define an instance object, no storage space (heap) allocations are made until the class method Alloc function and instance method init function implements the storage allocation of the instance object's structure in the heap, and Isa points to its class object, the parent class member variable and the corresponding class object member variable are initialized to 0 or nil


The above understanding can be confirmed by the following code and object variable structure analysis.
    • Test code
#import <Foundation/Foundation.h> #import <objc/runtime.h>  @interface aclass : nsobject {intACharCA;} - (void) PrintA;@end @implementation aclass - (void) printa{NSLog(@"I am class a~");}@end @interface bclass : aclass {intbCharCB;} - (void) Printb;@end @implementation bclass - (void) printb{NSLog(@"I am class b~");}@end//----------main----------intMainintargcConst Char* argv[]) {@autoreleasepool {///****** object model ******AClass *a = [[AClass alloc] init];        Bclass *b = [[Bclass alloc] init];        Bclass *b1;        [A PrintA];        [B PRINTB]; }return 0; }
    • View object variable structure (view by setting breakpoints into debug mode)

    • Isa pointer invocation diagram for class objects, meta classes, and instance objects (subclass is a instance of superclass)

(1) Root class is NSObject, NSObject no super class, superclass-nil

(2) Each class object has an Isa pointer to a unique meta class

(3) The ISA pointer for each meta-class object points to the meta-class object of NSObject

Message delivery and forwarding mechanisms

message Passing (Messaging): The process of passing data between objects and performing tasks

Objective-c the dynamic language of object-oriented and message-forwarding mechanism based on C language, it is necessary to use runtime system to dynamically create class and object for message sending and forwarding in addition to compiler.

Different languages have different function passing methods, C language-function pointers, C + +-function call (Reference) class member functions at compile time to determine its category, objective-c through the selector and block.

Objective-C强调消息传递而非方法调用。可以向一个对象传递消息,且不需要再编译期声明这些消息的处理方法。这些方法在运行时才确定。运行时(runtime)具体功能将在下面介绍。

[receiver message];
Instead of executing the code of the receiver object's message method immediately, it sends a message to receiver that is translated by the compiler to:

id obj_msgSend(id self, SEL op, …);

PS: The message call function also has special cases, such as other functions
Objc_msgsend_stret//Send message back to struct
Objc_msgsend_fpret//Return floating-point number
Objc_msgsendsuper//Send message to Super class

The SEL represents a method selector with the following structure: typedef struct objc_selector*SEL; the keyword @selector () can be used to obtain

The ID data structure is 第一部分:对象模型 already defined in.

obj_msgSend 发消息流程:

    • The corresponding class (class object) is obtained according to the Isa class object pointer of receiver object;
    • takes precedence over the cache (fast map) of the class object to find the message method, not find and then to methodlists (the dispatch table in the class, used to map the method and the actual memory address, and also includes a pointer to the parent class in the class) lookup;
    • If not found in the class image, then to Super_class search;
    • If you find the message this method , implement its implementation imp
    • If no message is found , message forwarding is performed (msg forwarding)

Method数据结构The runtime.h header file defines:

typedef struct objc_method *Method;{          SEL method_name; // 特殊的字符串,描述方法名, 可以通过关键字 @selector( ) 获取          char *method_types;          IMP method_imp;}

PS: Message forwarding is divided into two major stages, dynamic method resolution and the complete message forwarding mechanism (full forward mechanism).

Runtime System Functional Understanding

Runtime: After the program runs, the code that provides the support is called OC运行期环境(OC runtime) , it provides important functions for passing messages between objects (such as Objc_msgsend), and contains all the logic used to create instances of the class (that is, the storage structure and space for creating instance objects). Include Isa pointer to class object)

Runtime system is a C language to write dynamic link library, the core is the message distribution. The runtime mechanism includes object model, message passing and forwarding, method implementation mechanism and other runtime methods, which can realize dynamic creation of functions such as modifying class objects and objects, message passing and forwarding, dynamic realization of methods, method swizzling and so on.

Reference Resources

Effective OBJECTIVE-C 2.0
Objective-c object model and run-time
In-depth understanding of Objective-c's runtime mechanism
Dynamic characteristics of Objective-c

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

The object model and runtime mechanism of OBJECTIVE-C

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.