To create a NSMutableString, you can use +stringWithFormat:, as in the following example:
NSString *name = @"Nicola"; NSMutableString *str; str = [NSMutableString stringWithFormat: @"Hello, %@", name];While NSString's implementation of +stringWithFormat: returns a NSString, NSMutableString's implementation returns a NSMutableString. Static strings created with the @"..." construct are always immutable.
In practice, NSMutableStrings are not used very often, because usually if you want to modify a string you just create a new string derived from the one you already have.
The most interesting method of the NSMutableString class is possibly the method -appendString:. It takes as argument a NSString, and appends it to the receiver.
For example, the following code:
NSString *name = @"Nicola"; NSString *greeting = @"Hello"; NSMutableString *s; s = AUTORELEASE ([NSMutableString new]); [s appendString: greeting]; [s appendString: @", "]; [s appendString: name];(where we used new to create a new empty NSMutableString) produces the same result as the following one:
NSString *name = @"Nicola"; NSString *greeting = @"Hello"; NSMutableString *s; s = [NSMutableString stringWithFormat: @"%@, %@", greeting, name];