Initialization of the OC object

Results:

Alloc has memory, it has a pointer to it, init doesn’t do anything to the memory pointer.

Modify the code as follows:

You can see the print result as follows:

It can be alloc out a piece of memory space, p1, P2,p3 are three pointer addresses pointing to the same piece of memory space, but the addresses are in the stack, in the stack are continuous Pointers, 8 bytes apart.

1. How do alloc do that, init?

  • Three methods of analysis

(1) breakpoint tracking method ibobjc.a. dylib ‘objc_alloc:

Break points in codeAfter running, it pauses at a breakpoint,

Into the

You then access the underlying source code by adding a Symbolic Breakpoint

(2) Debug assembly objc_alloc

Enter X86 underlying assembly

Continue to break point to

Libobjc.a. dylib ‘+[NSObject alloc]:

The breakpoint can then be entered next

  • open source

(1) First enter the source code of alloc function

(2) In the alloc source code, then enter the _objc_rootAlloc, you can see

(3) The same operation is entered into the callAlloc method

There is a fork, and in order to analyze which way to go, we set the corresponding symbol breakpoint for each of the above processes,

We can’t run it directly yet, register Read X0 will give us an error because we’re dealing with subclasses and not superclasses, so we need to run into LGPerson’s breakpoint area and then open and run the breakpoint

  • Compilation and debugging of the underlying methods

Compiler optimizations in ARM64, x for 64-bit and w for 32-bit execute a function that results in x0, the position of the first argument

This is compiler optimization

What determines the size of an object’s memory: The member variable class isa is 8, which isa structure pointer type. Objc_class inherits from objc_object if(size<16) size =16 byte alignment algorithm (X+WORD_MASK) & ~WORD_MASK 8 byte alignment, an integer of 8

  • Alloc flowchart

A procedure for customizing class alloc:

By calling objc_alloc->callAlloc, there are two cases of callAlloc cache and no cache.

(1) When there is a cache: _objc_rootAllocWithZone -> _class_createInstanceFromZone -> instanceSize -> calloc -> initInstanceIsa

(2) When there is no cache: alloc method is called internally by objc_msgSend and _objc_rootAlloc -> callAlloc is executed internally. The following steps are the same as above.