in C I can simply declare an array like this:
int array[500];
to declare an array of size 500 which can then be filled later. Is it possibel to do the same thing in NSArray? I understand for the NSMutableArray there is the arrayWithCapacity class method to "create" and empty array (or at least declare the array to be filled later). Is there a way to do something similar for NSArray, since I know the exact size of my array I want to fill in the contents later in a "for" loop.
Thanks
Technically, int array[500];
does not create an empty array - it creates an array full of zeros. Since NSArray
s is immutable, you do need to use NSMutableArray
if you'd like to be able to populate it later.
You can make an array with a specific capacity, and then put objects into it, like this:
NSMutableArray *array = [NSMutableArray arrayWithCapacity:500];
for (int i = 0 ; i != 500 ; i++) {
[array addObject:@(i)];
}
Since NSMutableArray
is an NSArray
, you can create it in a method as NSMutableArray*
, and then return it as NSArray*
to the callers.
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