Item 3: Prefer Literal Syntax over the Equivalent Methods
1.
The literal syntax also works for expressions:
2.
However, you need to be aware of one thing when creating arrays using the literal syntax. If any of the objects is nil, an exception is thrown
NSArray *arrayA = [NSArray arrayWithObjects:
object1, object2, object3, nil];
NSArray *arrayB = @[object1, object2, object3];
Now consider the scenario in which object1
and object3
point to valid Objective-C objects, but object2
is nil. The literal array, arrayB
, will cause the exception to be thrown. However, arrayA
will still be created but will contain only object1
. The reason is that thearrayWithObjects:
method looks through the variadic arguments until it hits nil, which is sooner than expected.
This subtle difference means that literals are much safer. It’s much better that an exception is thrown, causing a probable application crash, rather than creating an array having fewer than the expected number of objects in it. A programmer error most likely caused nil to be inserted into the array, and the exception means that the bug can be found more easily.
3.
Also, in the case of strings, arrays, and dictionaries, only immutable variants can be created with the literal syntax. If a mutable variant is required, a mutable copy must be taken, like so:
NSMutableArray *mutable = [@[@1, @2, @3, @4, @5] mutableCopy];