Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSArray initialization with numbers

Tags:

cocoa

nsarray

I was wondering how do I go about creating an NSArray with say numbers 1-100 to be used in a UIPickerView.

I know from other programming classes I could do:

int array[100];
for (int i=1, i<=100, i++)
   array[i]=i;

But I am not sure how to something equivalent with NSArray, instead of manually typing in all the values. I searched it online and I saw someone did it with calloc and was unsure if that was the best method, or if I could wrap the int into a NSNumber somehow and have each NSNumber go into my array. And if I was to do this procedure, would I then create a NSMutableArray and addObject each time running through the loop? I want these values loaded whenever the user goes to the screen.

like image 984
jet Avatar asked Dec 01 '09 19:12

jet


1 Answers

Either:

NSArray * array = [NSArray array];
for ( int i = 1 ; i <= 100 ; i ++ )
    array = [array arrayByAddingObject:[NSNumber numberWithInt:i]];

[array retain];

Or:

NSMutableArray * array = [[NSMutableArray alloc] initWithCapacity:100];
for ( int i = 1 ; i <= 100 ; i ++ )
    [array addObject:[NSNumber numberWithInt:i]];

...should do what you want. If this is something you're doing often, you may consider creating a category for constructing an array containing a range.

like image 65
Skirwan Avatar answered Oct 20 '22 05:10

Skirwan