Push object onto end of array using new literal syntax

nsmutablearray, objective-c, objective-c-literals

Solution

Take a look at the documentation for the new literal syntax. When you assign into an array using a subscript, the call is translated into the `setObject:atIndexedSubscript:` method call:

NSMutableArray *foo = …;
foo[0] = @"bar"; // => [foo setObject:@"bar" atIndexedSubscript:0];

If you had your own mutable array implementation, you could add a special case to the `setObject:atIndexedSubscript:` method to grow the array when assigning past the array size. I very much doubt the default `NSMutableArray` implementation does anything like it, most probably you’d just get an exception about index being out of bounds. And this is indeed what `NSMutableArray` does, see the reference documentation:

If the index is equal to count the element is added to the end of the array, growing the array.

Thank you Martin for the heads-up!

Problem

PHP has: ``` arr[] = 'Push this onto my array'; ``` Where the string will be added to the end of the array. Is there any equivalent of this in the new Objective-C literal syntax? The most succinct way I can think of doing it is: ``` arr[arr.count] = @"Add me"; ``` but maybe there's something better out there?

Original source