Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

A little knowledge every day will keep us going steadily. Use Clang to restore the underlying implementation of Objective-C code to discover what the nature of the object is! Open the main.m function and write the following code:

#import <Foundation/Foundation.h> #import <objc/runtime.h> @interface LGPerson : NSObject @property (nonatomic, strong) NSString *Name; @end @implementation LGPerson @end int main(int argc, const char * argv[]) { @autoreleasepool { NSLog(@"Hello, World!" ); } return 0; }Copy the code

Using the clang command, generate the main. CPP file

clang -rewrite-objc main.m -o main.cpp
Copy the code

Through the analysis of CPP files, to explore the nature of the object to find the definition and implementation of LGPerson, you can find

typedef struct objc_object LGPerson;

struct LGPerson_IMPL { 
    struct NSObject_IMPL NSObject_IVARS;
    NSString *_Name; 
};
Copy the code
  • LGPersonIs defined asobjc_objecttype
  • LGPerson_IMPLisLGPersonThe underlying implementation of
  • LGPerson_IMPLThe nestedNSObject_IMPL structure
  • Structure nesting is equivalent to pseudo-inheritance

If you go to the definition and implementation of NSObject, you can see that

typedef struct objc_object NSObject; 

struct NSObject_IMPL { 
    Class isa;
};
Copy the code
  • NSObjectIs defined asobjc_objecttype
  • NSObject_IMPLisNSObjectThe underlying implementation of
  • There is only oneClassType of a member variableisa

Find the definition and implementation of Class, you can find

typedef struct objc_class *Class;

struct objc_class { 
    Class _Nonnull isa __attribute__((deprecated)); 
} __attribute__((unavailable));
Copy the code
  • ClassType, essentiallyobjc_classStructure pointer, accounted for8 bytes

Find the implementation of objc_Object

struct objc_object { 
    Class _Nonnull isa __attribute__((deprecated));
};
Copy the code
  • objc_objectThere is only oneClassType of a member variableisa
  • The underlying implementation of all objects essentially comes fromobjc_objectThe structure of the body

Conclusion:

  • The essence of an object is a structure
  • A class is also an object, and is essentially a structure
  • Everything is an object, everything has isa
  • Isa is essentially a structure pointer that takes 8 bytes
  • The underlying implementation of all objects is essentially derived from the objC_Object structure