Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an empty NSArray

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

like image 758
samuelschaefer Avatar asked Nov 03 '22 23:11

samuelschaefer


1 Answers

Technically, int array[500]; does not create an empty array - it creates an array full of zeros. Since NSArrays 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.

like image 57
Sergey Kalinichenko Avatar answered Dec 03 '22 16:12

Sergey Kalinichenko