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.
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.
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
You should do like this
int i = 0;
NSString *str = [[NSString alloc] initWithFormat:@"%d",i];
myString = [myString stringByAppendingString:str];
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];
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...
NSMutableString
if you want to use appendString
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.
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];