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?
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 And this is indeed what NSMutableArray
implementation does anything like it, most probably you’d just get an exception about index being out of bounds.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!
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