Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create array of ints

I'm struggling to create an array of ints in objective c.

the way I'd do this is javascript would be:

arr = new Array ( 1, 2, 3, 4, 3, 2, 2 );

I need to use an NSMutableArray, as the values need to be updated (it's a tile map for a game).

How can I do this?

like image 851
rob g Avatar asked Mar 06 '26 06:03

rob g


2 Answers

Does the array need to change length?

If not, why not use a normal array of ints:

int arr[] = { 1, 2, 3, 4, 3, 2, 2};

Note that an NSArray (or subclass thereof) doesn't hold int types natively, you have to create an NSNumber object.

If you really need an Objective-C style array, then use this:

int vals[] = { 1, 2, 3, 4, 3, 2, 2};  // you still need this
int n = sizeof(vals) / sizeof(vals[0]);

[NSMutableArray* array = [[NSMutableArray alloc] initWithCapacity:n];
for (int i = 0; i < n; ++i) {
    [array addObject: [NSNumber numberWithInt:vals[i]]];
}
like image 198
Alnitak Avatar answered Mar 07 '26 19:03

Alnitak


For an NSMutableArray (though a C-style array may be preferable, as suggested by Alnitak), you need to do something like this:

NSMutableArray *array = [NSMutableArray arrayWithObjects: [NSNumber numberWithInt: 1], [NSNumber numberWithInt:2], nil];

(You can put as many as you want into that constructor, just separate them with commas and end with a nil.)

You could also make an empty array ([NSMutableArray array]) and then fill it with your ints using [array addObject:[NSNumber numberWithInt:1]].

If you need a 2D version, take a look here.

like image 38
Jesse Rusak Avatar answered Mar 07 '26 21:03

Jesse Rusak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!