How to add an integer to an array?

It should be pretty simple, but I was wondering how to add an integer to an array?

I know that I can add lines as follows:

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

But I think I can’t just add integers:

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

At least the compiler is not happy with this and tells me that I am doing cast without saying so.

Any explanation would be much appreciated.

+5
source share
3 answers

Yes, it's right. The compiler will not accept your code like this. The difference is as follows:

If you write @"a String", it will be the same as if you created a string and auto-implemented it. This way you create the object with @"a String".

(: ). , .

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

, :

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

, , . . , Xcode.

EDIT:

[yourArray addObject:@3];

NSNumber.

@[@1, @2];

NSArray, 2 NSNumber 1 2.

+27

NSNumbers, , : [NSNumber numberWithInteger: myInt];

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

[trArray addObject: yourNumber];
+7

, :

NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:[NSString stringWithFormat:@"%d",1]];
[[array objectAtIndex:0] intValue];
+4

All Articles