Http://macresearch.org/difference-between-alloc-init-and-new:
1. In actual development, new is rarely used. Generally, all we see when creating objects is [[className alloc] init].
But it does not mean that you will not be exposed to new. In some code, you will still see [className new],
You may also be asked this question during the interview.
2. What is the difference between them?
Let's look at the source code:
- + New
- {
- Id newObject = (* _ alloc) (Class) self, 0 );
- Class metaClass = self-> isa;
- If (class_getVersion (metaClass)> 1)
- Return [newObject init];
- Else
- Return newObject;
- }
-
- // While alloc/init is like this:
- + Alloc
- {
- Return (* _ zoneAlloc) (Class) self, 0, malloc_default_zone ());
- }
- -Init
- {
- Return self;
- }
Through the source code, we found that [className new] is basically equivalent to [[className alloc] init];
The difference is that zone is used when alloc allocates memory.
What is this zone?
When allocating memory to objects, it allocates the associated objects to an adjacent memory area, so as to consume a small amount of money during calls and increase the processing speed of the program;
3. Why is new not recommended?
I don't know if you have found it: if you use new, the initialization method is fixed and you can only call init.
What if you want to call initXXX? No! It is said that the initial design fully draws on the Smalltalk syntax.
Legend has it that allocFromZone was available at that time: This method,
However, This method requires passing the parameter id myCompanion = [[TheClass allocFromZone: [self zone] init];
This method is as follows:
- + AllocFromZone :( void *) z
- {
- Return (* _ zoneAlloc) (Class) self, 0, z );
- }
-
- // Simplified to the following:
- + Alloc
- {
- Return (* _ zoneAlloc) (Class) self, 0, malloc_default_zone ());
- }
However, there is a problem: This method only allocates memory to the object and does not initialize instance variables.
Does it return to the processing method like new: Call the init method implicitly inside the method?
Later I found that "display call is better than implicit call", so I separated the two methods.
In summary, new and alloc/init functions almost the same, allocating memory and completing initialization.
The difference is that the new method can only use the default init method to complete initialization,
You can use other custom initialization methods using alloc.