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.



The ability to find the definition of an object structure in a objc.h file, such as ISA with the object structure as class, and class as the Objc_class struct type pointer, as seen below.



Objc_class is the class object structure that we understand. It also contains a pointer to the structure of an Isa class object.



The final realization of classes and objects is a data structure, (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. typedef struct objc_object *id;
;
    • Class type definition
 
 
 
/// An opaque type that represents an Objective-C class.
typedef struct objc_class *Class;
    • Class (object) structure
 
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;
Relationship of Class (class object), meta-Class (Meta-class object), and instance object


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






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


    • to understand this:

      The class contains Class objects and meta-class objects, which are defined by the class object structure and form the entire information of the class. When you define an instance object, it does not make any storage space (heap) allocations, until you call the class method Alloc function and the instance method of the Init function to implement the structure storage allocation of the instance object in the heap. And Point Isa 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
{
    int a;
    char cA;
}

- (void)printA;

@end

@implementation AClass

- (void)printA
{
    NSLog(@"I am class A~");
}

@end

@interface BClass : AClass
{
    int b;
    char cB;
}

- (void)printB;

@end

@implementation BClass

- (void)printB
{
    NSLog(@"I am class B~");
}

@end


// ---------- main ----------
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // ******对象模型初探******
        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 superclass. Nil Superclass



(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 feature and message forwarding mechanism based on C language. Besides the compiler, it is necessary to use the runtime system to dynamically create classes and objects for message sending and forwarding.



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 emphasizes message passing, not method invocation.

The ability to pass messages to an object without the need to declare the processing of those messages at compile time.

These methods are determined at execution time. The execution time (runtime) details are described below.


[receiver message];
Code that does not immediately execute the message method of the receiver object. Instead, a message is sent 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, such as the following:typedef struct objc_selector*SEL。the keyword @selector () can be used to obtain



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



obj_msgSend message flow:



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 to methodlists (the schedule table in the class, used for mapping methods and actual memory addresses.) At the same time, the class also contains pointers to the parent class) to find;
Suppose not found in the class image. Again to Super_class find.
Assuming that a message is found this way, implement its implementation imp
Suppose the message cannot be found. Message forwarding is performed (msg forwarding)


Method data structure The runtime.h header file defines:



typedef struct objc_method * Method;
struct objc_method {
           SEL method_name; // special string. Descriptive narrative method name, which can be obtained by keyword @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 executes. The code that provides support is calledOC执行期环境(OC runtime), it provides an important function for passing messages between objects (for example, 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, including a pointer to the "Class object" by Isa)



Runtime system is a C language to write dynamic link library, the core is the message distribution. The runtime mechanism contains the object model. Message delivery and forwarding. method implementation mechanisms and other execution-time methods. Ability to dynamically create changes such as objects and objects, such as message delivery and forwarding, dynamic implementation of methods, method swizzling and other functions.



# # # # # # # # # # # #Objective-c How does the program generate the execution information?
For an OC. M program file, enter the command in the terminal:
gcc -framework Foundation main.m -o p1
Of course. Executing the command is:./p1
Then, through the Otool tool to get the target files (including headers, loading instructions, individual segment) in the execution of information (there is a special segment save)
otool -o p1



PS We are able to understand information such as the structure of meta-class objects and class objects in the object model, such as the following, by acquiring execution-time information. Can clearly see the class object list and meta-class mapping relationships, structure information


 
p1:
Contents of (__DATA,__objc_classlist) section
0000000100001098 0x100001310
           isa 0x1000012e8
    superclass 0x0
         cache 0x0
        vtable 0x0
          data 0x100001160 (struct class_ro_t *)
                    flags 0x0
            instanceStart 8
             instanceSize 13
                 reserved 0x0
               ivarLayout 0x0
                     name 0x100000f60 AClass
              baseMethods 0x1000010f8 (struct method_list_t *)
          entsize 24
            count 1
              name 0x100000f6e printA
            types 0x100000f91 [email protected]0:8
              imp 0x100000d90
            baseProtocols 0x0
                    ivars 0x100001118
                    entsize 32
                      count 2
              offset 0x1000012c8 8
                name 0x100000f75 a
                type 0x100000f99 i
            alignment 2
                size 4
              offset 0x1000012d0 12
                name 0x100000f77 cA
                type 0x100000f9b c
            alignment 0
                size 1
           weakIvarLayout 0x0
           baseProperties 0x0
Meta Class
           isa 0x0
    superclass 0x0
         cache 0x0
        vtable 0x0
          data 0x1000010b0 (struct class_ro_t *)
                    flags 0x1 RO_META
            instanceStart 40
             instanceSize 40
                 reserved 0x0
               ivarLayout 0x0
                     name 0x100000f60 AClass
              baseMethods 0x0 (struct method_list_t *)
            baseProtocols 0x0
                    ivars 0x0
           weakIvarLayout 0x0
           baseProperties 0x0
00000001000010a0 0x100001360
           isa 0x100001338
    superclass 0x100001310
         cache 0x0
        vtable 0x0
          data 0x100001258 (struct class_ro_t *)
                    flags 0x0
            instanceStart 16
             instanceSize 21
                 reserved 0x0
               ivarLayout 0x0
                     name 0x100000f67 BClass
              baseMethods 0x1000011f0 (struct method_list_t *)
          entsize 24
            count 1
              name 0x100000f7a printB
            types 0x100000f91 [email protected]0:8
              imp 0x100000dc0
            baseProtocols 0x0
                    ivars 0x100001210
                    entsize 32
                      count 2
              offset 0x1000012d8 16
                name 0x100000f81 b
                type 0x100000f99 i
            alignment 2
                size 4
              offset 0x1000012e0 20
                name 0x100000f83 cB
                type 0x100000f9b c
            alignment 0
                size 1
           weakIvarLayout 0x0
           baseProperties 0x0
Meta Class
           isa 0x0
    superclass 0x1000012e8
         cache 0x0
        vtable 0x0
          data 0x1000011a8 (struct class_ro_t *)
                    flags 0x1 RO_META
            instanceStart 40
             instanceSize 40
                 reserved 0x0
               ivarLayout 0x0
                     name 0x100000f67 BClass
              baseMethods 0x0 (struct method_list_t *)
            baseProtocols 0x0
                    ivars 0x0
           weakIvarLayout 0x0
           baseProperties 0x0
Contents of (__DATA,__objc_classrefs) section
00000001000012b8 0x100001310
00000001000012c0 0x100001360
Contents of (__DATA,__objc_imageinfo) section
  version 0
    flags 0x0
References Resources


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



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.