tags:

views:

755

answers:

1

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.

+2  A: 

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.

Skirwan
Don't forget to release the array in the second example, since you have allocked it. (For that matter, why retain it in the first example?)
Peter Hosey
Lacking context, I imagined a use case that required keeping it around. But yes, in either case the result will need to be released at some point.
Skirwan
Careful using convenience constructors in loops. The first example will create 100 temporary arrays, each larger than the last.
Preston
@Skirwan if you are planning on keeping the object around, use [[NSArray alloc] init] instead - less lines of code.
retainCount