Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 930
Bot Avatar asked Jan 25 '13 17:01

Bot


People also ask

What is the difference between NSArray and array?

Array is a struct, therefore it is a value type in Swift. NSArray is an immutable Objective C class, therefore it is a reference type in Swift and it is bridged to Array<AnyObject> . NSMutableArray is the mutable subclass of NSArray . Because foo changes the local value of a and bar changes the reference.

How do you define an array of objects in Objective C?

Creating an Array Object For example: NSArray *myColors; myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil]; The above code creates a new array object called myColors and initializes it with four constant string objects containing the strings "Red", "Green", "Blue" and "Yellow".

Is NSArray ordered?

The answer is yes, the order of the elements of an array will be maintained - because an array is an ordered collection of items, just like a string is an ordered sequence of characters...


1 Answers

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.

like image 69
Martin R Avatar answered Sep 28 '22 08:09

Martin R