5

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.

Daniel
  • 20,420
  • 10
  • 92
  • 149

1 Answers1

7

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]

Community
  • 1
  • 1
Alaeddine
  • 6,104
  • 3
  • 28
  • 45
  • Adding up to this answer, regarding [NSArray array], it generates an empty immutable array. It's quite useless to do this obviously (like using new), but it changes when using a NSMutableArray. The thing is, as @Aladin mentioned, now that we have ARC, It does not make any difference. – Erakk Jul 16 '15 at 14:47
  • Comes down to syntax usage I think and preference. – Robert J. Clegg Jul 16 '15 at 14:50
  • It is not completely useless, you can do something like `NSArray *arr = [NSArray array]; NSArray *arr2 = [arr arrayByAddingObject:@"ha!"];`. It may be useful.. at some point.. i guess – Daniel Jul 16 '15 at 14:51