Objective-C Allocating Arrays with @ [] and initWithObjects

A work colleague and I are struggling to answer correctly the exact difference between two different ways to create an array:

NSArray *array1 = @[@"this is my first entry",@"this is my second entry"];
NSArray *array2 = [[NSArray alloc] initWithObjects:@"first entry",@"second entry",nil];


  • Can anyone explain this?
  • What is the preferred usage and why?
  • Another interesting question: does it work the same for NSString, NSDictionary, etc.

Thank you in advance!


source to share

3 answers

The first method is preferred. Not just because it is "modern" (which means little), shorter and less error prone.

There is a small problem with initWithObjects: if you manage to include a pointer to an object that is effectively null, then initWithObjects will use that as a nil endpoint, whereas literal syntax will throw an exception.

NSString* text1 = textField1.text;
NSString* text2 = textField2.text;
NSString* text3 = textField3.text;

NSArray* array1 = [[NSArray alloc] initWithObjects:text1, text2, text3, nil];
NSArray* array2 = @[text1, text2, text3];


If textField2 == nil and therefore text2 = nil, array1 will be an array with one element, not the three you expected, which can cause all sorts of troublesome troubleshooting. array2 throws an exception, so you can fix your code.



I agree with gnasher729

alloc allocates a chunk of memory to hold the object and returns a pointer. To avoid a memory leak, the user also needs to properly release the allocated object . Therefore, the first option will be preferable for local use of any object.

In principle, any object is selected

  • save object
  • increase service life
  • increase access area

Look for the alloc , init methods to learn more .



They are both good. The first is a more "modern" literal syntax and is preferred. And yes, it works the same for NSString and NSDictionary only in more modern literal syntax.




All Articles