The difference between new and array initialization

Is there a difference between the initializations of [NSArray new] and [NSArray array] ?

array seems to be part of the implementation of NSArray , while new belongs to NSObject .

+5
source share
1 answer

new = alloc + init

This method is a combination of alloc and init. Like alloc, it initializes the isa instance variable of the new object so that it points to the data structure of the class. He then calls the init method to complete the initialization process.

Reference to the NSObject Class

+new is literally implemented as:

 + (id) new { return [[self alloc] init]; } 

and new do not support custom initializers (e.g. initWithObjects ), so alloc + init more explicit than new

So now we are talking about:

[NSArray array] vs [[NSArray alloc] init]

The main difference between the two is that you are not using ARC (Automatic Link Counting). The first returns a saved and auto-implemented object. The second returns an object that is only being saved. Therefore, in the first case, you would like to save it if you wanted to keep it longer than the current cycle of the cycle. in the second case, you would like to free or auto-advertisement if you do not want to save it.

Now that we have ARC, this makes a difference. Basically, in the ARC code, it doesn't matter which one you use.

But keep in mind that [NSArray array] returns an empty immutable array, so using array with NSMutableArray makes more sense

For more information:

alloc, init, and new in Objective-C

Using alloc initialization instead of new

The difference between [NSMutableArray array] vs [[NSMutableArray alloc] init]

+7
source

All Articles