The alloc and init methods are called in the main function

CZPerson *p1 = [CZPerson alloc];
CZPerson *p2 = [p1 init];
CZPerson *p3 = [p1 init];

NSLog(@"%@-%p-%p",p1,p1,&p1);
NSLog(@"%@-%p-%p",p2,p2,&p2);
NSLog(@"%@-%p-%p",p3,p3,&p3);
Copy the code

After careful analysis

  • 1Alloc allocates memory for the object, and init does not change the memory address
  • 2Init changes the address of the pointer
  • 3The initial size of the object is 16 bytes

Init doesn’t seem to be doing anything, so what’s left for us to do is just look at what alloc does?

Let’s explore…

The assembler debugging

2. Open assembly and choose DEBUG -> DebugWorkflow -> Always Show Disassembly

Display as shown in figureThe underlying method objc_alloc in objC.a. dylib is calledObjc_alloc: _objc_rootAllocWithZone: _objc_rootAllocWithZoneContinue debugging _objc_rootAllocWithZone and find that the function calloc is calledPreliminary ALLOC flow is obtained through assembly debugging

graph TD
objc_alloc --> _objc_rootAllocWithZone --> calloc --> ...

To be perfect…

But these methods seem a little different from the underlying methods, so let’s use the underlying source code to verify that the current process is correct

The source code to debug

Based on objC4 source code debugging source through train

According to the previous assembly debugging, the underlying method that alloc calls first is objc_alloc. Global search is conducted in the source code project to quickly locate the underlying methods related to alloc below, and then make breakpoints on all relevant methods to check the call sequence, so that the alloc call process can be easily obtained. The sequence is shown as follows:The alloC flow chart is as follows

graph TD
alloc.or.objc_alloc --> _objc_rootAlloc --> callAlloc --> ...

To be perfect…