41

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);
}
Pang
  • 9,564
  • 146
  • 81
  • 122
saikamesh
  • 4,569
  • 11
  • 53
  • 93

3 Answers3

80

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)];
}
Pang
  • 9,564
  • 146
  • 81
  • 122
pgb
  • 24,813
  • 12
  • 83
  • 113
8

Here is another way to add object in array if you are working with immutable array. Which is thread safe.

You can use arrayByAddingObject method. Some times it's much better. Here is discussion about it: NSMutableArray vs NSArray which is better

Community
  • 1
  • 1
Danil
  • 1,780
  • 17
  • 24
  • `[array arrayByAddingObject:@"mažiukas"];` does not add the new element. – Darius Miliauskas Mar 07 '15 at 03:12
  • 1
    @DariusMiliauskas but it creates (and returns) a new array which contains all elements from original array plus new one. Sometimes it might be very helpful (for example, if you prefer working with non-mutable data-structures, like NSArray). – Sergei Belous Jul 05 '18 at 13:15
4

Convert your NSArray to NSMutableArray, and then you can add values dynamically:

NSMutableArray *mutableStringArray = [stringArray mutableCopy];
[mutableStringArray addObject:@"theNewElement"];
Darius Miliauskas
  • 3,391
  • 4
  • 35
  • 53