The realization of the OC
OC objects, classes are mainly based on C, C++ structure to achieve. OC code prepared, the underlying implementation is actually C, C++ code.
The nature of OC objects
Struct NSObject_IMPL {Class isa; struct NSObject_IMPL {Class isa; };Copy the code
How much memory does an NSObject take up?
NSObject has only one isa pointer inside it. In 64-bit environments, Pointers take up 8 bytes, so NSObject actually uses only 8 bytes. However, in ios 64-bit operating systems, memory allocation rules are multiples of 16, so an NSObject takes up 16 bytes. (This can be verified by the malloc_size function)
Use clang to convert OC classes into C++ files
Generate C++ file xcrun-sdk iphoneos clang-arch arm64 on Xcode specifying arm64 -rewrite-objc main.m -o main-arm64.cppCopy the code
Calculate memory size by function
#import <objc/runtime.h>
#import <malloc/malloc.h>NSObject *obj = [[NSObject alloc] init]; // Calculate how much memory the object needs"%zu",class_getInstanceSize([NSObject class])); // Calculate how much memory is actually allocated NSLog(@"%zu",malloc_size((__bridge const void *)(obj)));
Copy the code
Xcode looks at memory data in real time
LLDB Displays memory data in real time
OC Object classification
1. Instance object
An instance object is an object that the class alloc produces, and each call to alloc generates a new instance object. Isa pointer to other member variables NSObject *object = [[NSObject alloc] init];Copy the code
2. Class object
Each class has one and only one class object in memory, obtained through the class method. Isa pointer Superclass pointer attribute information object method information protocol information member variable information Class objectClass = [NSObject Class];Copy the code
3. Meta-class objects
A metaclass object is an object of a class. Each class has one and only one metaclass object in memory, obtained through object_getClass(class object). The structure of a metaclass is the same as that of a class, but the address is different and the value is stored differently. Isa pointer Superclass pointer class method information#import <objc/runtime.h>
Class objectmetaclass = object_getClass([NSObject class]);
Copy the code
added
1. The class method returns only a class object, not a metaclass object, even though [[NSObject class] class] is the same.
2. Object_getClass returns the object to which the isa pointer to the passed object points, which is the truest class object.
3. Check whether class is a metaclass
BOOL result = class_ismetaClass([NSObject class]);
Copy the code
4. If this article violates privacy or other things, please contact me, I will rectify or delete in the first time.