Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push object onto end of array using new literal syntax

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?

like image 634
serverpunk Avatar asked Oct 15 '12 07:10

serverpunk


1 Answers

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!

like image 118
zoul Avatar answered Oct 11 '22 19:10

zoul