3

a working colleague and me are struggling to properly answer the exact difference between two different ways of creating 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 way of using and why?
  • Another interesting question would be: does it work the same for NSString, NSDictionary, etc classes?

Thank you in advance!

3 Answers 3

8

The first way is preferred. Not only because it is "modern" (which doesn't mean much), shorter and less error prone.

There is a subtle problem with initWithObjects: If you manage to include an object pointer that is actually nil, then initWithObjects will use this as the trailing nil pointer, while the 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 instead of the three that you expected, which could cause all kinds of hard to find bugs. array2 will throw an exception so you can fix your code.

Sign up to request clarification or add additional context in comments.

3 Comments

Why will there be only one element instead of two?
Please see the comment by @Student for additional information.
What other kind of Objects can be done using the a literal kind of syntanx which don't require manual alloc init? P.S. technically you categorize the two types as 'literal' and 'alloc-init'? [gnasher sendThankYou]
1

I do agree with gnasher729

alloc allocates a chunk of memory to hold the object, and returns the pointer. To avoid memory leak, user has to properly release the allocated object also. So first one will be preferred for local use of any object.

Basically any object is being allocated

  1. to retain the object
  2. to increase its life time
  3. to increase its area of access

To know more please search for alloc, init methods.

2 Comments

@gnasher829 & @Student: if you have a class property, e.g. objectArray and fill it in the init using the literal @{} method -- will there be any problems in further usage of the array throughout the class?
Your statement that "array1 will be accessible only in the method" is incorrect. Both arrays will act the same. So, @Flowinho, the literal syntax will create arrays you can use throughout the class.
0

They're both fine. The first one is more "modern" literal syntax and more preferred. And yes it works the same for NSString and NSDictionary just more of the modern literal syntax.

http://clang.llvm.org/docs/ObjectiveCLiterals.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.