The difference between new and alloc in object c

In the object-c basic tutorial book, you can always see code similar to the following, and I am a little novice wondering, what is the difference, do they all look the same. I searched online and found some ideas, here are the first picks.
    className* object = [className new];
or
    className* object = [[className alloc] init];
The background shows that new is an old-fashioned way of writing. Later, it was found that only one new was not easy to use, so alloc and init were introduced. , Retaining new is backward compatibility, and it is often a simpler way of writing. In fact, it is the same, new calls alloc and init internally.
Source code:
+ new
{
id newObject = (*_alloc)((Class)self, 0);
Class metaClass = self->isa;
if (class_getVersion(metaClass) > 1)
    return [newObject init];
else
    return newObject;
}

+ alloc
{
return (*_zoneAlloc)((Class)self, 0, malloc_default_zone());
}

- init
{
    return self;
}


[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 an object, it allocates the associated object to an adjacent memory area, so that it consumes little cost when calling, which improves the processing speed of the program.
Why should alloc and init be separated?
1. Yes Use multiple init methods
2. Explicit calls are better than implicit calls"
If you really don't need to use other init functions, such as initWithString, just use [Nsobject alloc] init], then the new method is more convenient
* new doesn't support custom initializers (like initWithString)
* alloc-init is more explicit than new

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326860125&siteId=291194637