objlv
objlv

Reputation: 601

Create array using for loop

I'm trying to generate integer array using for loop. Here is my code:

int total = 20;

for(int x = 0; x < total; x++)
{
   NSArray arr = [NSArray arrayWithObjects: [NSNumber numberWithInt:total]];
}

With the above implementation I get only one object in array, the last one. What to do so arr to contain the numbers from 1 to 20 ?

Upvotes: 1

Views: 5382

Answers (6)

Andreas Helgegren
Andreas Helgegren

Reputation: 1678

int total = 20;

NSMutableArray *arr = [[NSMutableArray alloc] init];
for(int x = 0; x < total; x++)
{
   [arr addObject:[NSNumber numberWithInt:x]];
}

// release the array when you are done with it.

Upvotes: 2

Parag Bafna
Parag Bafna

Reputation: 22930

Every time you are creating a new NSArray and assigning it to NSArray *arr. +arrayWithObjects: method create a new array. NSArray is not mutable , you should use NSMutableArray.

NSArray creates static arrays, and NSMutableArray creates dynamic arrays.

NSMuatbleArray *arr = [[NSMutableArray alloc]init];
for(int i =0 ; i<20 ; ++i)
{
[array addObject:[NSNumber numberWithInt:i]];
}

Upvotes: 0

Roman Temchenko
Roman Temchenko

Reputation: 1806

NSMutableArray *arr = [NSMutablearray arrayWithCapacity:total];
for(int x = 0; x < total; x++)
{
   [arr addObject:[NSNumber numberWithInt:x]];
}

At every loop you created new array with one object. in this example you create array once and than just add objects to it.

Upvotes: 0

Lorenzo B
Lorenzo B

Reputation: 33428

NSArray is an immutable class (it means you cannot add/remove objects runtime) and what you are doing here is quite strange. You create a new array inside the loop.

You could use a NSMutableArray but externally to the loop. In this manner you have a reference outside the loop and you can add objects to it. NSMutableArray is mutable. You can change objects runtime.

NSMutableArray* numberArray = [[NSMutableArray alloc] init];

for(int x = 0; x < total; x++)
{
   [numberArray addObject:[NSSnumber numberWithInt:x]];
}

Upvotes: 1

tallybear
tallybear

Reputation: 417

You're recreating the array every time. Make the NSArray an iVar or initialize it outside of the loop.

Upvotes: 1

Jeremy
Jeremy

Reputation: 9030

You should initialize your array outside of the loop rather than inside the loop.

Change your code to this:

int total = 20;
NSMutableArray *arr = [NSMutableArray array];
for(int x = 0; x < total; x++)
   [arr addObject:[NSNumber numberWithInt:x]];

Upvotes: 2

Related Questions