12

I want to convet int to string in objective c how to do that.

my code.

for (i=0; i<=200; i=i+10) {
    // here i want to convet the value of i into string how to do this 

}   

Thanks in Advance.

1
  • i have another string variable named myWord I want to assign i value to it....... Sep 29, 2010 at 12:19

3 Answers 3

14

Try this:

NSMutableString *myWord = [[NSMutableString alloc] init];
for (int i=0; i<=200; i=i+10) {
    [myWord appendString:[NSString stringWithFormat:@"%d", i]];
    //...
}
//do something with myWord...
[myWord release];

NSInteger is simply a typedef to the int or long data types on 32/64-bit systems.

1
  • 2
    n13's answer below is the modern variant and far more elegant
    – Oly Dungey
    Sep 3, 2014 at 15:11
14
NSInteger n = 13;
NSString string = @(n).stringValue;

Reference see Objective-C literals - literals remove lots of ugly boilerplate code cluttering up your codebase: http://clang.llvm.org/docs/ObjectiveCLiterals.html

4
  • 1
    Cool, thanks for introducing me to the easy way with the new syntax
    – Oly Dungey
    Sep 3, 2014 at 15:09
  • This is actually slower and less memory efficient since you create an instance of NSNumber every time you wish to get a string value. Did a benchmark with 1000000 iterations and got 0.924962 seconds with the NSNumber approach and got 0.668426 seconds using the stringWithFormat approach. This is just a consideration if you'd be using it in a huge loop.
    – Majster
    Sep 12, 2014 at 7:10
  • ^ Interesting benchmark, but I'd have expected it to perform worse. A 30% difference is not that much. Obviously, don't do this if you're converting thousands or tens of thousand of numbers to String. Huge loop of number to String conversion sounds like bad code to me, no matter how you do the conversion.
    – n13
    Sep 23, 2014 at 4:32
  • Much better solution, thank you. This is also cross-compatible with 32- and 64-bit, and futureproof for any other format string weirdness!
    – Ky -
    Jul 15, 2015 at 15:21
2

You may want to declare myWord out of the loop as NSMutableString.

Not the answer you're looking for? Browse other questions tagged or ask your own question.