Search code examples
objective-cnsarrayobjective-c-literals

Using @[array, of, items] vs [NSArray arrayWithObjects:]


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?


Solution

  • 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.