7

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.

1
  • Just indent your code with atleast 4 spaces and it will become a code block. Commented Dec 1, 2009 at 19:40

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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?)
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.
Careful using convenience constructors in loops. The first example will create 100 temporary arrays, each larger than the last.
@Skirwan if you are planning on keeping the object around, use [[NSArray alloc] init] instead - less lines of code.
It would be nice to edit and note that the first option is inefficient, and expensive in terms of memory and cpu cycles. You actually allocate a new NSArray 100 times, to create an NSArray of 100 numbers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.