Today, my colleague told me that the new project requires a unified [[XXX alloc]init] way to create, do not use new.
So the baby's heart is curious, for what, in my cognition, new and Alloc init is the same role Ah,
So in the online search, found a valuable article, excerpts down to share with you.
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; if (class_getversion (Metaclass) > 1) return [NewObject init]; else return newObject; } //And alloc/init like this: + alloc {return (*_zonealloc) ((Class) self, 0, malloc_default_zone ());
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); } It was 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.
With June to share ~
The difference between IOS new and Alloc Init