mogio
mogio

Reputation: 843

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

Upvotes: 5

Views: 17212

Answers (4)

Mario
Mario

Reputation: 4520

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];

Upvotes: 10

anjani kp
anjani kp

Reputation: 63

too late. but u can do the following too.

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

Upvotes: 0

CRD
CRD

Reputation: 53000

First start with a C array:

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

Second, if you need an NSArray loop through this array and create one:

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

You can wrap the second piece of code up as a category on NSArray if you're doing it a lot.

Upvotes: 0

Anne
Anne

Reputation: 27073

Nice short alternative for looping specific integers:

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

Upvotes: 0

Related Questions