C lens - array with numbers

Is there a better way to populate an array with numbers than I use? It's crazy how much I need to write to populate the array with numbers so that they can be used to calculate in a loop. This is easier in other C languages ​​such as 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);
}

Hope there is a shorter way ... I just want to fill the array with ints ... can't be so hard

+5
source share
4 answers

I think you need to use NSNumber for NSArray. If you want to use ints, I think you have to use the c array:

NSInteger myArray[20];

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

  //do something
 }

NSNumber, though, I think the best approach for this language. At the very least, you can do a quick enumeration to shorten the code a bit:

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

 //do something....

}

EDIT:

3 . , , NSNumbers NSArrays:

NSNumber *n = @100;

NSArray *array = @[@100,@50,@10];
+10

:

NSArray *numbers = [@"1000,237,2673" componentsSeparatedByString:@","];
for (NSString *i in numbers) {
    [i intValue]; // Do something.
}
0

C:

NSInteger myCArray = { 1000, 237, 2673 };
// calculate number of elements
NSUInteger myCArrayLength = sizeof(myCArray) / sizeof(NSInteger;

Secondly, if you need a loop NSArraythrough this array and create it:

NSMutableArray *myNSArray = [NSMutableArray arrayWithCapacity:myCArrayLength];
for(NSUInteger ix = 0; ix < myCArrayLength; ix++)
   [myNSArray addObject:[NSNumber numberWithInteger:myCArray[ix]];

You can wrap the second part of the code as a category on NSArrayif you do this a lot.

0
source

too late. but you can also do the following.

int total = 0;
nsarray *myArray = @[@1.8,@100,@299.8]; 
for(nsnumber *num in myArray){
 total+=num;
}
0
source

All Articles