NSArray adding elements

saikamesh picture saikamesh · Apr 22, 2009 · Viewed 94.8k times · Source

I have to create a dynamic NSArray, that is, I don't know the size of the array or what elements the array is going to have. The elements need to be added to the array dynamically. I looked at the NSArray class reference. There is a method called arrayWithObjects, which should be used at the time of initializing the array itself. But I don't know how to achieve what I need to do.

I need to do some thing like the following:

NSArray *stringArray = [[NSArray init] alloc] ;  
for (int i = 0; i < data.size; i++){  
    stringArray.at(i) = getData(i);
}

Answer

pgb picture pgb · Apr 22, 2009

If you create an NSArray you won't be able to add elements to it, since it's immutable. You should try using NSMutableArray instead.

Also, you inverted the order of alloc and init. alloc creates an instance and init initializes it.

The code would look something like this (assuming getData is a global function):

NSMutableArray *stringArray = [[NSMutableArray alloc] init];
for(int i=0; i< data.size; i++){
   [stringArray addObject:getData(i)];
}