views:

196

answers:

6

I am converting an integer into String.

I did a search but here but it is not useful.

int i;
NSString *str;
str = [NSString stringWithFormat:@"%d",i];

[myString appendString:str];

It is not working throwing an error.

A: 

Try this:

str = [NSString stringWithFormat:@"%i",i];

edit: you need to use the proper placeholder for the type of variable you want to insert into the string.

edit2: appendString works for NSMutableStrings only. Either use NSMutable string or create a new string by using stringByAppendingString

Toastor
%i isn't it strange.. !
org.life.java
Actually, @"%d" also works with int.
Eric MORAND
True. But it will add a completely useless .000000 to the output :)
Toastor
%d adds zeros? i have never heard that.
taskinoor
You're right. My bad, again. I confused it with %f, which does add the zeroes. Just tried it again to make sure.
Toastor
A: 

You should do like this

    int i = 0;
NSString *str = [[NSString alloc] initWithFormat:@"%d",i];
myString = [myString stringByAppendingString:str];
Abramodj
stringWithFormat is a class method on NSString that is the equivalent of your `alloc` / `init` pair.
Patrick Johnmeyer
...except that it also autoreleases the returned string. If you `alloc` then you must remember to `release` afterwards.
walkytalky
+3  A: 

Make sure that myString is a NSMutableString otherwise it will not work as NSString is im-mutable and does not have appendString:.

If myString is in fact a NSString, you can create a NSMutableString like so:

NSMutableString *myString = [NSMutableString stringWithString:@"Here's My String!"];

or create a mutable copy of your NSString:

NSMutableString *myMutableString = [myString mutableCopy];
Joshua
A: 

[NSString stringWithFormat: @"%d", x];

gyurisc
+1  A: 
    int i = 0;
NSMutableString *myString = [NSMutableString string];
NSString* myNewString = [NSString stringWithFormat:@"%d", i];
[myString appendString:myNewString];
NSLog(@"myString = %@", myString);  // result: myString = 0

A few things here...

  • Make sure you assign your int a value, otherwise you'll get a (seemingly) random unsigned integer value
  • Make sure myString is a NSMutableString if you want to use appendString
  • For myNewString, it's more streamlined (and less confusing) to have the variable declaration on the same line as it's allocation.

See the question "How to do string conversions in Objective-C?" for other coercions like this.

Philip Regan
+1  A: 

There is no reason that it should not work. This is a perfect code.
Points to be care: myString should be mutable string.

int i;
NSString *str;
NSMutableString *myString;

str = [NSString stringWithFormat:@"%d",i];
*%d or %i both is ok.

[myString appendString:str];
Tauquir