Today we’ll take a look at the iOS object creation process, the underlying alloc init process, and how it works:
Person *p = [[Person alloc] init];
According to the assembly notation we will go to the bottom here:
You can see that the bottom layer is in objec_alloc format, and then it goes to the next step
It’s going to go to our _objc_rootAlloc, which returns callAlloc, and then it’s going to go in there
If CLS ->ISA()->hasCustomAWZ() returns YES, meaning there ISA default allocWithZone method, then allocWithZone is applied directly to the class. Apply for memory space. Then go to the _objc_rootAllocWithZone method
You can see the _class_createInstanceFromZone method returned directly
So this is the core of our alloc object
First it creates a size_t, which is how much memory we need to create first
In instanceSize, you can see that the requested memory size is 16. If the size is less than 16, the system will automatically align the memory.
We then create an object with id obj to request a pointer address from the system
This step is just the address applied to obj. At this point, our Person object does not correspond to the relevant address. The next step is the association step
At this point, our initialized Person object is associated with the requested memory pointer address
Go back to CLS ->ISA()->hasCustomAWZ() if NO is returned
CLS ->canAllocFast() specifies whether the current class supports fast alloc, and if so, calls calloc to initInstanceIsa.
The detailed flow chart is as follows: