Next: 1.6 Reading and Saving Up: 1 NSString Previous: 1.4 Converting to and

1.5 NSMutableString

NSStrings are immutable objects, that is, once you create an NSString, you can not modify it. This allows the GNUstep libraries to optimise the NSString code. If you need to be able to modify a string, you should use a special subclass of NSString, called NSMutableString. Since NSMutableString is a subclass of NSString, you can use a NSMutableString wherever a NSString could be used. But, a NSMutableString responds to methods which allow you to modify the string directly, a thing you can't do with a generic NSString.

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];


Next: 1.6 Reading and Saving Up: 1 NSString Previous: 1.4 Converting to and
2008-01-16