some_id
some_id

Reputation: 29896

Creating an array of integers or NSUIntegers in objective C

How is an array created for integers or NSUIntegers in objective c?

The thing is I want an array which I can change often(NSMutableArray ?) but when I try to addObject:someInt or someNSUInteger I get a warning about "without cast" and when that code executes the app crashes.

What is the fastest way to set this up? and I dont know the size of the array. It should be dynamic.

Upvotes: 2

Views: 4869

Answers (3)

vikingosegundo
vikingosegundo

Reputation: 52227

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

read it back

int i = [[array objectsAtIndex:0] intValue];

or successive:

NSMutableArray *array = [NSMutableArray array];
for(int i =0; i<10; i++) {
    NSNumber *number = [NSNumber numberWithInt:i];
    [array addObject: number];
}

With modern literal syntax you could also do:

NSMutableArray *array = [@[@0, @1, @2] mutableCopy];
int i = [array[0] intValue];

Upvotes: 3

dijipiji
dijipiji

Reputation: 3109

If you just want a reference to a bunch of pure int constants and want to avoid the overhead of NSNumber objects and don't need to modify your array you can try:

const int SOME_NUMBERS[] = {1,2,3};

and reference it later on with, e.g.:

printf("\nSOME_NUMBERS[1] %i\n",SOME_NUMBERS[1]);

Upvotes: 3

Jason F
Jason F

Reputation: 454

NSUInteger is nothing but a typedef-ed unsigned int. NSMutableArrays only accept objects, which I think is your problem. Try using NSNumber instead.

Upvotes: 5

Related Questions