Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - Array With Numbers

Is there a nicer way to fill an array with numbers than what I use? It's crazy how much I got to write just to fill an array with numbers so they can be used for a calculation in a loop. This is easier in other C based languages like PHP, As3, or Java.

NSArray *myArray = [NSArray arrayWithObjects:  
                    [NSNumber numberWithInt:1000],[NSNumber numberWithInt:237], [NSNumber numberWithInt:2673], nil];

int total = 0;
for(int i = 0; i < [myArray count]; i += 1 ){
    total += [[myArray objectAtIndex: i]intValue];
    NSLog(@"%i", total);
}

Hopefully there is a shorter way... I just want to fill an array with ints... cant be that hard

like image 472
mogio Avatar asked Jun 24 '12 16:06

mogio


1 Answers

I guess you have to use NSNumber for an NSArray. If you want to use ints I guess you'd have to use a c array:

NSInteger myArray[20];

for (int i=0;i<20;i++) {
  int num=myArray[i];

  //do something
 }

NSNumber though is I guess the better approach for this language. At least you can do fast enumeration to shorten code a bit:

for (NSNumber *n in myArray) {
 int num = [n intValue];

 //do something....

}

EDIT:

The question has been asked 3 years ago. There have been new literals established to make it easier to create objects like NSNumbers or NSArrays:

NSNumber *n = @100;

or

NSArray *array = @[@100,@50,@10];
like image 169
Mario Avatar answered Sep 28 '22 10:09

Mario