Reputation: 20315
Is there a general purpose function in Objective-C that I can plug into my project to simplify concatenating NSString
s and int
s?
Upvotes: 27
Views: 64497
Reputation: 164
It seems the real answer is no - there is no easy and short way to concatenate NSStrings with Objective C - nothing similar to using the '+' operator in C# and Java.
Upvotes: -1
Reputation: 17170
Both answers are correct. If you want to concatenate multiple strings and integers use NSMutableString's appendFormat.
NSMutableString* aString = [NSMutableString stringWithFormat:@"String with one int %d", myInt]; // does not need to be released. Needs to be retained if you need to keep use it after the current function.
[aString appendFormat:@"... now has another int: %d", myInt];
Upvotes: 30
Reputation: 171
string1,x , these are declared as a string object and integer variable respectively. and if you want to combine both the values and to append int values to a string object and to assign the result to a new string then do as follows.
NSString *string1=@"Hello";
int x=10;
NSString *string2=[string1 stringByAppendingFormat:@"%d ",x];
NSLog(@"string2 is %@",string2);
//NSLog(@"string2 is %@",string2); is used to check the string2 value at console ;
Upvotes: 3
Reputation: 181270
NSString *s =
[
[NSString alloc]
initWithFormat:@"Concatenate an int %d with a string %@",
12, @"My Concatenated String"
];
I know you're probably looking for a shorter answer, but this is what I would use.
Upvotes: 3
Reputation: 4641
[NSString stringWithFormat:@"THIS IS A STRING WITH AN INT: %d", myInt];
That's typically how I do it.
Upvotes: 36