9

There seem to be different methods of instantiating NSArrays (same for NSDictionary and some others).

I know:

  1. [NSArray array]
  2. [NSArray new]
  3. @[]
  4. [[NSArray alloc] init]

For readability reasons I usually stick with [NSArray array], but what is the difference between all those, do they all really do the same?

Kirit Modi
  • 23,155
  • 15
  • 89
  • 112
MarkHim
  • 5,686
  • 5
  • 32
  • 64
  • Compare http://stackoverflow.com/questions/5423211/difference-between-nsmutablearray-array-vs-nsmutablearray-alloc-init, http://stackoverflow.com/questions/14527489/using-array-of-items-vs-nsarray-arraywithobjects and http://stackoverflow.com/questions/719877/use-of-alloc-init-instead-of-new. – Martin R Oct 23 '15 at 07:52
  • And how exactly is the question related to [swift]? – Martin R Oct 23 '15 at 07:55

2 Answers2

18

Results are same for all of them, you get a new empty immutable array. These methods have different memory management implications though. ARC makes no difference in the end, but before ARC you would have to use the right version or send appropriate retain, release or autorelease messages.

  • [NSArray new], [[NSArray alloc] init] return an array with retain count is 1. Before ARC you would have to release or autorelease that array or you'd leak memory.

  • [NSArray array], @[] return an already autoreleased array (retain count is 0). If you want it to stick around without ARC you'd have to manually retain it or it would be deallocated when the current autorelease pool gets popped.

tuledev
  • 10,177
  • 4
  • 29
  • 49
Sven
  • 22,475
  • 4
  • 52
  • 71
8
  1. [NSArray array] : Create and return an empty array

  2. [NSArray new] : alloc, init and return a NSArray object

  3. @[] : Same as 1.

  4. [[NSArray alloc] init] : Same as 2.

Different between [NSArray array] and [[NSArray alloc] init] is if there are non-ARC:

  • [NSArray array] is an autorelease object. You have to call retain if you want to keep it. E.g when you return an array.

  • [[NSArray alloc] init] is an retained object. So you don't have to call retain more if you want keep it.

With ARC, they are same.

tuledev
  • 10,177
  • 4
  • 29
  • 49
  • it'd make more sense if you could also explain when we should be aware of difference between `[NSArray array];` and `[[NSArray alloc] init];` for instance and why. – holex Oct 23 '15 at 08:39
  • @holex. Thank you. I improved my answer. – tuledev Oct 23 '15 at 08:47