views:

4817

answers:

4

Concatenating strings and ints seems like a real chore in Objective C. I'm new to the language, so can someone help me with a sort of general purpose function that I can plug into my project and simplify this and not require a lot of typing (where other languages could just use a +)?

Thanks very much!

+8  A: 
[NSString stringWithFormat:@"THIS IS A STRING WITH AN INT: %d", myInt];

That's typically how I do it.

Genericrich
Also look into localizedStringWithFormat: and initWithFormat:locale: when formatting a number for use on screen.
Chris Lundie
+3  A: 
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.

Pablo Santa Cruz
Is this the same as [NSString stringWithFormat:] ?
Nocturne
With this method you will need to release the string when you're done with it.
Outlaw Programmer
@Debajit, it's basically, the same. You'll have to release the string after you use it.
Pablo Santa Cruz
+3  A: 

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];
Roger Nolan
A: 

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.

enter code here

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 ;

ksnr