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
.
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.
+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]