Modifying strings, Storing strings – Apple WebObjects 3.5 User Manual
Page 195

Commonly Used String Methods
195
Modifying Strings
Warning:
The following methods are not supported by NSString. They are
available only to NSMutableString objects.
– appendFormat:
Appends a constructed string to the receiver. Creates the new
string by using the
stringWithFormat:
method with the arguments
listed. For example, in the following code excerpt, if you assume
the variable
guestName
contains the string “Rena”, then
message
has
the resulting contents “Hi, Rena!”:
id message = [NSMutableString stringWithString:@"Hi"];
[message appendFormat:@", %@!", guestName];
– appendString:
Adds the characters of a specified string to the end of the receiver.
For example, the following statements create an
NSMutableString and append another string to its initial value:
id mutableString = [NSMutableString stringWithFormat:@"Hello "];
[mutableString appendString:@"world!"];
mutableString
has the resulting contents “Hello world!”.
– setString:
Replaces the characters of the receiver with those in a specified
string. For example, the following statement replaces the contents
of an NSMutableString with the empty string:
[mutableString setString:@""];
Storing Strings
– writeToFile:atomically:
Writes the string to a specified file, returning YES on success and
NO on failure. If YES is specified for
atomically:
, this method writes
the string to an auxiliary file and then renames the auxiliary file to
the specified path. In this way, it ensures that the contents of the
specified path do not become corrupted if the system crashes
during writing. The resulting file is suitable for use with
stringWithContentsOfFile:
. For example, the following code excerpt reads
the contents of an error log stored in a file, appends a new error to
the log, and saves the updated log to the same file:
id errorLog = [NSString stringWithContentsOfFile:errorPath];
id newErrorLog = [errorLog stringByAppendingFormat:@"%@: %@.\n",
timeStamp, @"premature end of file."];
[newErrorLog writeToFile:errorPath atomically:YES];