Is there a difference between the initializations [NSArray new]
and [NSArray array]
?
array
seems to be part of the implementation of NSArray
while new
belongs to NSObject
.
Answer. Array declaration tells the compiler about the size and data type of the array so that the compiler can reserve the required memory for the array. This reserved memory is still empty. Array Initialisation assigns values to the array elements i.e. it stores values in the memory reserved for the array elements.
Answer: The new keyword is used to allocate the space in dynamic memory for the storage of data and functions belonging to an object while defining an array in Java.
There are two ways to specify initializers for arrays: With C89-style initializers, array elements must be initialized in subscript order. Using designated initializers, which allow you to specify the values of the subscript elements to be initialized, array elements can be initialized in any order.
Also lists are containers for elements having differing data types but arrays are used as containers for elements of the same data type.
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 it points to the class data structure. It then invokes the init method to complete the initialization process.
NSObject Class Reference
+new
is implemented quite literally as:
+ (id) new
{
return [[self alloc] init];
}
and new
doesn't support custom initializers (like initWithObjects
), so alloc + init
is more explicit than new
So the question now is about:
[NSArray array] vs [[NSArray alloc] init]
The main difference between these is if you're not using ARC (Automatic Reference Counting). The first one returns a retained and autoreleased object. The second one returns an object that is only retained. So in the first case, you would want to retain it if you wanted to keep it around for longer than the current run loop. In the second case, you would want to release or autorelease it if you didn't want to keep it around.
Now that we have ARC, this changes things. Basically, in ARC code, it doesn't matter which of these 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
Use of alloc init instead of new
Difference between [NSMutableArray array] vs [[NSMutableArray alloc] init]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With