English Explanation: Http://macresearch.org/difference-between-alloc-init-and-new
1. New is seldom used in real-world development, generally creating objects we see all [[ClassName alloc] init]
But it doesn't mean you won't be exposed to new, and you'll see [ClassName new] in some code,
There is also the possibility of being asked this question when you go to an interview.
2. So what's the difference between them?
We look at the source:
- + New
- {
- ID newObject = (*_alloc) ((Class) self, 0);
- Class Metaclass = self->isa;
- < span class= "keyword" style= "margin:0px; padding:0px; Border:none; Color:rgb (0,102,153); Background-color:inherit; Font-weight:bold ">if (Class_getversion (Metaclass) > 1)
- return [newobject init];
- < span class= "keyword" style= "margin:0px; padding:0px; Border:none; Color:rgb (0,102,153); Background-color:inherit; Font-weight:bold ">else
- return NewObject;
- }
- //And alloc/init like this:
- + Alloc
- {
- return ( *_zonealloc) ((Class) self, 0, malloc_default_zone ());
- }
- -Init
- {
- return Self ;
- }
Through the source we find that [className new] is basically equivalent to [[ClassName alloc] init];
The difference is that the zone is used when alloc allocates memory.
What is this zone?
When allocating memory to an object, the associated object is allocated to an adjacent area of memory, so that the cost of the call is very low and the processing speed of the program is improved.
3. And why is it not recommended to use new?
I don't know if you've found it: if you use new, the initialization method is fixed and can only call init.
And what do you want to call initxxx? No way It is said that the original design was completely borrowed from the Smalltalk syntax.
Legend has it that time has Allocfromzone: This method,
But this method needs to pass a parameter id mycompanion = [[Theclass allocfromzone:[self Zone]] init];
This method looks like this:
- + allocfromzone: ( void *) Z
- {
- return ( *_zonealloc) ((Class) self, 0, z);
- }
- //later simplified to the following:
- + Alloc
- {
- return ( *_zonealloc) ((Class) self, 0, malloc_default_zone ());
- }
However, there is a problem: This method simply allocates memory to the object and does not initialize the instance variable.
Is it going back to new like this: implicitly invoking the Init method inside a method?
Later it was found that "show calls are always better than implicit calls", so the two methods were later separated.
In summary, new and alloc/init are functionally almost identical, allocating memory and completing initialization.
The difference is that the initialization can only be done with the default Init method in new mode,
Other custom initialization methods can be used in a alloc way.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The difference between new and alloc/init in OC