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?
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.
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".
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With