12

Is there a difference between

NSArray *myArray = @[objectOne, objectTwo, objectThree];

and

NSArray *myArray = [NSArray arrayWithObjects:objectOne, objectTwo, objectThree, nil];

Is one preferred over the other?

jscs
  • 63,095
  • 13
  • 148
  • 192
Bot
  • 11,728
  • 11
  • 72
  • 129
  • possible duplicate of [Difference between @\[\] and \[NSArray arrayWithObjects:\]](http://stackoverflow.com/questions/12834504/difference-between-and-nsarray-arraywithobjects) – jscs Jan 25 '13 at 18:47
  • Sorry, I even searched google and here. Maybe the symbols were messing up the search that is why i wasn't getting anything relevant. – Bot Jan 25 '13 at 18:57
  • It's not meant to be a recrimination. Actually, that comment is created by the system on my behalf when I vote to close. – jscs Jan 25 '13 at 19:26

2 Answers2

32

They are almost identical, but not completely. The Clang documentation on Objective-C Literals states:

Array literal expressions expand to calls to +[NSArray arrayWithObjects:count:], which validates that all objects are non-nil. The variadic form, +[NSArray arrayWithObjects:] uses nil as an argument list terminator, which can lead to malformed array objects.

So

NSArray *myArray = @[objectOne, objectTwo, objectThree];

would throw a runtime exception if objectTwo == nil, but

NSArray *myArray = [NSArray arrayWithObjects:objectOne, objectTwo, objectThree, nil];

would create an array with one element in that case.

Martin R
  • 510,973
  • 84
  • 1,183
  • 1,314
  • 5
    +1 This is the correct answer; the difference is subtle, but nevertheless the two are different. – jlehr Jan 25 '13 at 18:18
  • I'm not sure what "malformed array objects" means, but the arrays would be perfectly fine, just not the length you thought they would be. Also, I sometimes intentionally exploit the nil termination behavior, to have an optional last element that is only included if it is not `nil`. – newacct Jan 25 '13 at 20:52
-2

No. At compile time the @[...] literals will be changed to arrayWithObjects:

The only difference is that @[...] is only supported in newer versions of the LLVM compiler.

DrummerB
  • 39,275
  • 12
  • 103
  • 141