Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSArray adding elements

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); } 
like image 440
saikamesh Avatar asked Apr 22 '09 18:04

saikamesh


People also ask

How do I add values to an array in Objective-C?

The mutable version is NSMutableArray , which will allow you to append values. You can't add primitives like int to an NSArray or NSMutableArray class; they only hold objects. The NSNumber class is designed for this situation. You are leaking memory each time you are allocating an array.

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

Can NSArray contain nil?

arrays can't contain nil.

What's a difference between NSArray and NSSet?

The main difference is that NSArray is for an ordered collection and NSSet is for an unordered collection. There are several articles out there that talk about the difference in speed between the two, like this one. If you're iterating through an unordered collection, NSSet is great.


2 Answers

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)]; } 
like image 98
pgb Avatar answered Sep 18 '22 19:09

pgb


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

like image 42
Danil Avatar answered Sep 19 '22 19:09

Danil