12

I'm a java guy coming over to Objective-C. In java, to add a variable to a string you'd have to do something along the lines of:

someString = "This string is equal to " + someNumber + ".";

I can't figure out how to do it in Objective-C though. I have an NSMutableString that I'd like to add to the middle of a string. How do I go about doing this?

I've tried:

NSString *someText = @"Lorem ipsum " + someMutableString;
NSString *someText = @"Lorem ipsum " + [someMutableString stringForm];

and a few other things, none of which seem to work. Also interchanged the +s with ,s.

Peter Kazazes
  • 3,600
  • 7
  • 31
  • 60

4 Answers4

30

You can use appendString:, but in general, I prefer:

NSString *someText = [NSString stringWithFormat: @"Lorem ipsum %@", someMutableString];
NSString *someString = [NSString stringWithFormat: @"This is string is equal to %d.", someInt];
NSString *someOtherString = [NSString stringWithFormat: @"This is string is equal to %@.", someNSNumber];

or, alternatively:

NSString *someOtherString = [NSString stringWithFormat: @"This is string is equal to %d.", [someNSNumber intValue]];

etc...

These strings are autoreleased, so take care not to lose their value. If necessary, retain or copy them and release them yourself later.

Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94
8

Try this:

NSMutableString * string1 = [[NSMutableString alloc] initWithString:@"this is my string"];

[string1 appendString:@" with more strings attached"];

//release when done
[string1 release];
Louie
  • 5,920
  • 5
  • 31
  • 45
6

You need to use stringByAppendingString

NSString* string = [[NSString alloc] initWithString:@"some string"];
string = [string stringByAppendingString:@" Sweet!"];

Don't forget to [string release]; when your done of course.

Trevor
  • 11,269
  • 2
  • 33
  • 40
  • 1
    Your memory management is messed up. It's the original string created by `alloc` that you need to release, but you're throwing that away (leaking it) and replacing it with the result of `stringByAppendingString:`, which should not be released. – Chuck Aug 15 '11 at 20:30
  • I realize that I may be confused by memory management here, but isn't my 2nd statement pointing to the same block of memory, in which I am just reassigning the value to the existing value plus the appended string? – Trevor Aug 16 '11 at 12:50
  • 1
    Nope, it's two different different objects at two different memory locations. Plain NSStrings can't change their value, so `stringByAppendingString:` returns a new string with the original string's value plus the appended value. – Chuck Aug 16 '11 at 15:56
  • 1
    Since ARC this would not be a problem anymore? – d00dle Feb 14 '15 at 21:38
0
NSMutableString *string = [[NSMutableString alloc] init];

[string appendFormat:@"more text %@", object ];
Rami
  • 7,879
  • 12
  • 36
  • 66