NSArray initialization with numbers
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 some开发者_开发问答thing 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.
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.
精彩评论