Comparison of new alloc and init in IOS

  • 2021-10-27 09:23:16
  • OfStack

Comparison of new, alloc and init in IOS

1. new is rarely used in actual development, and all we see when creating objects is [[className alloc] init]

But that doesn't mean you won't be exposed to new, and you'll still see [className new] in some code,

And when you go to an interview, you are likely to be asked this question.

2. So what's 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; 
} 
 
// And  alloc/init  Like this:  
+ alloc 
{ 
return (*_zoneAlloc)((Class)self, 0, malloc_default_zone()); 
} 
- init 
{ 
return self; 
} 

Through the source code, we find that [className new] is basically equivalent to [[className alloc] init];

The only difference is that alloc uses zone when allocating memory.

What is this zone?

When allocating memory to objects, the associated objects are allocated to an adjacent memory area, so as to consume little cost when calling and improve the processing speed of programs;

3. Why not recommend new?

I don't know if you have noticed that if you use new, the initialization method is fixed and can only call init.

And what if you want to call initXXX? No way! It is said that the original design was completely borrowed from Smalltalk syntax.

Legend has it that there was allocFromZone at that time: this method,

But this method needs to pass the 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 reduced 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 the instance variable.

Is it going back to the new approach of implicitly calling the init method inside the method?

Later, it was discovered that "explicit calls are better than implicit calls", so the two methods were separated later.

In summary, new and alloc/init are functionally almost identical, allocating memory and initializing.

The difference is that the initialization can only be completed by the default init method when using new.

Other customized initialization methods can be used in alloc.

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: