38

Possible Duplicate:
How to convert from int to string in objective c: example code…

How to convert integer to string in Objective C?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Ranjeet Sajwan
  • 1,925
  • 2
  • 28
  • 60
  • 3
    The other question that you linked to as duplicate has the same title as this one and it has 9000+ views, but it does not answer directly and in a clear way the question from the title: how to convert an `int` to a `string` in Objecive-C. The other question is complex and it is hard to extract the real answer from it. It is more probable actually that someone finding it will learn how (not) to compare strings than how to convert an int to a NSString. – Florin Aug 06 '10 at 08:45

3 Answers3

84
NSArray *myArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3]];

Update for new Objective-C syntax:

NSArray *myArray = @[@1, @2, @3];

Those two declarations are identical from the compiler's perspective.

if you're just wanting to use an integer in a string for putting into a textbox or something:

int myInteger = 5;
NSString* myNewString = [NSString stringWithFormat:@"%i", myInteger];
peelman
  • 1,339
  • 1
  • 11
  • 13
17

If you really want to use String:

NSString *number = [[NSString alloc] initWithFormat:@"%d", 123];

But I would recommend using NSNumber:

NSNumber *number = [[NSNumber alloc] initWithInt:123];

Then just add it to the array.

[array addObject:number];

Don't forget to release it after that, since you created it above.

[number release];
Florin
  • 1,844
  • 2
  • 16
  • 21
13
NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];
zengr
  • 38,346
  • 37
  • 130
  • 192
Christoffer
  • 25,035
  • 18
  • 53
  • 77
  • I receive the next alert: Values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead, why? – Sebastian Paduano Dec 26 '18 at 16:43