Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an integer to an array?

This must be quite basic, but I was wondering how to add an integer to an array?

I know I can add strings like this:

NSMutableArray *trArray = [[NSMutableArray alloc] init];
[trArray addObject:@"0"];
[trArray addObject:@"1"];
[trArray addObject:@"2"];
[trArray addObject:@"3"];

But I guess I can't simply add integers like so:

NSMutableArray *trArray = [[NSMutableArray alloc] init];
[trArray addObject:0];
[trArray addObject:1];
[trArray addObject:2];
[trArray addObject:3];

At least the compiler isn't happy with that and tells me that I'm doing a cast without having told it so.

Any explanations would be very much appreciated.

like image 364
n.evermind Avatar asked Apr 29 '11 20:04

n.evermind


2 Answers

Yes that's right. The compiler won't accept your code like this. The difference is the following:

If you write @"a String", it's the same as if you created a string and autoreleased it. So you create an object by using @"a String".

But an array can only store objects (more precise: pointers to object). So you have to create objects which store your integer.

NSNumber *anumber = [NSNumber numberWithInteger:4];
[yourArray addObject:anumber];

To retrive the integer again, do it like this

NSNumber anumber = [yourArray objectAtIndex:6];
int yourInteger = [anumber intValue];

I hope my answer helps you to understand why it doesn't work. You can't cast an integer to a pointer. And that is the warning you get from Xcode.

EDIT:

It is now also possible to write the following

[yourArray addObject:@3];

which is a shortcut to create a NSNumber. The same syntax is available for arrays

@[@1, @2];

will give you an NSArray containing 2 NSNumber objects with the values 1 and 2.

like image 83
Sandro Meier Avatar answered Oct 04 '22 21:10

Sandro Meier


You have to use NSNumbers I think, try adding these objects to your array: [NSNumber numberWithInteger:myInt];

NSMutableArray *trArray = [[NSMutableArray alloc] init];     
NSNumber *yourNumber = [[NSNumber alloc] numberWithInt:5];

[trArray addObject: yourNumber];
like image 21
mservidio Avatar answered Oct 04 '22 22:10

mservidio