code

Let’s take a look at the print

Person *p1 = [Person alloc]; Person *p2 = [p1 init]; Person *p3 = [p1 init]; NSLog(@"%@ - %p - %p", p1, p1, &p1); NSLog(@"%@ - %p - %p", p2, p2, &p2); NSLog(@"%@ - %p - %p", p3, p3, &p3); //<Person: 0x6000022f4160> -0x6000022f4160-0x7ffee7a11078 //<Person: 0x6000022f4160 0x6000022f4160> - 0x6000022f4160 - 0x7ffee7a11070 //<Person: 0x6000022f4160> - 0x6000022f4160 - 0x7ffee7a11068Copy the code

%p — p1 is the address of the print object

%p — &p1 prints the address of P1 in the address space

Three pointer variables point to the same memory space, p1, P2, and P3 are in the stack space, so each pointer variable address is different; Since it is allocated in stack space, the stack space is from high to low; Since the pointer size is 8 bytes for 64-bit devices, 0x8 is subtracted from 0x7FFee7A11078.

In fact,init doesn’t do anything, it just gives the developer an interface to use the factory pattern,alloc is to allocate memory, and new is equal to calling alloc and then init.

The source code

The source code validates this

New source + (id)new {id newObject = (*_alloc)((Class)self, 0); Class metaClass = self->isa; if (class_getVersion(metaClass) > 1) return [newObject init]; else return newObject; + (id)alloc {return (*_zoneAlloc)((Class)self, 0, malloc_default_zone()); } - (id)init { return self; }Copy the code

Alloc process

Alloc is mainly responsible for creating memory, and its core process is as follows:

  1. Figure out how much memory space you needsize = cls->instanceSize(extraBytes);
  2. Apply for memory Apply for memory from the system and return the address pointerobj = (id)calloc(1, size);
  3. The ISA binding is associated with the corresponding classobj->initInstanceIsa(cls, hasCxxDtor);

conclusion

If you don’t override the init method, using new will take the parent init method; If we override the init method in our custom class, using new would go to the method that we override, but if we do our own custom initWithXXX, then new would call super Init, go to the parent init method, not the custom initWithXXX method.

Finally, the official source code and official documents of Apple are attached