The difference between NSArray.array / .new / @ [] / alloc-init

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

I know:

  • [NSArray array]
  • [NSArray new]
  • @[]
  • [[NSArray alloc] init]

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

+7
ios objective-c nsarray
source share
2 answers

The result is the same for all of them, you get a new empty immutable array. However, different methods have different consequences for memory management. Using ARC, it doesn't make any difference at the end, but before ARC you have to use the correct version or send the appropriate messages about saving, releasing or autoload.

[NSArray new] and [[NSArray alloc] init] return an array with a saving of +1. Before ARC, you have to release or auto-detect this array or memory leak.

[NSArray array] and @[] return an already auto-implemented array (save the value 0). If you want it to remain without ARC, you would have to manually save it or it would be released when the current autostart is deleted.

+11
source share
  • [NSArray array] : create and return an empty array

  • [NSArray new] : alloc , init and return an NSArray object

  • @[] : Same as 1.

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

There are differences between [NSArray array] and [[NSArray alloc] init] if non-ARC exists:

  • [NSArray array] - an abstract abstract object. You must call retain if you want to save it. For example, when you return array.

  • [[NSArray alloc] init] is a saved object. Therefore, you no longer need to call retain if you want to save it.

They are the same with ARC.

+7
source share

All Articles